0% found this document useful (0 votes)
4 views93 pages

WS Unit II Notes

The document outlines web security principles, focusing on user privacy and web server security. It discusses the threats to privacy from web technologies, the importance of strong passwords, and techniques for protecting personal information online. Additionally, it covers the implications of user-provided information, web logs, cookies, and privacy-protecting strategies.

Uploaded by

niharthree03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views93 pages

WS Unit II Notes

The document outlines web security principles, focusing on user privacy and web server security. It discusses the threats to privacy from web technologies, the importance of strong passwords, and techniques for protecting personal information online. Additionally, it covers the implications of user-provided information, web logs, cookies, and privacy-protecting strategies.

Uploaded by

niharthree03
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

WEB SECURITY

UNIT - II
Outline:
1. Privacy and Security for Users
• The Web’s War on Your Privacy
• Privacy-Protecting Techniques
• Privacy-Protecting Technologies
• Backups and Antitheft
2. Web Server Security
• Physical Security for Servers
• Host Security for Servers
• Securing Web Applications

Privacy and Security for Users


1. The Web’s War on Your Privacy
• The Web is bidirectional: users watch content, while web servers monitor user
activity.
• Each page visit is typically recorded by a computer, contributing to a growing user
profile.
• Visiting different types of sites (e.g., parenting, consumer electronics) allows systems
to infer interests and behavior.
• Registration with email addresses often leads to marketing emails and “special
offers.”

Web Opportunities vs. Privacy Costs


• The Web benefits consumers but also empowers:
o Marketers
o Sales organizations
o Tricksters and criminals
• Unlike billboards (which measure traffic volume), web advertising collects detailed
personal data:
o Location
o Internet access type
o Browsing history
o Email addresses
• Web ads are measurable and analyzable, but this requires extensive data collection,
reducing privacy.

Technology and Privacy


• The Internet was designed to transfer information, not protect privacy.

Web Security By [Link] - 1-


• Many web technologies enable tracking, often invisibly.
• This chapter introduces privacy threats.
• Later chapters (9 and 10) discuss privacy-protection techniques and software.

Understanding Privacy
• Privacy definitions vary.
• Merriam-Webster defines privacy as:
o Being apart from observation
o Freedom from unauthorized intrusion

The Tort of Privacy


• In 1890, Warren and Brandeis argued for a legal right to privacy.
• Privacy protects individuals from:
o Undesired publicity
o Exposure of personal matters without consent
• Key principles:
o Truth is not a defense
o Lack of malice is not a defense

Four Privacy Torts in U.S. Law


1. Privacy intrusion
o Intruding into a private sphere.
2. Disclosure of private facts
o Publishing private information with no public interest.
3. Portrayal of information in false light
o True or false information that misleads.
4. Appropriation
o Using a person’s name or likeness commercially without permission.
• These torts do not fully address computer-age privacy threats.

Informational Privacy (Westin)


• Alan Westin (1967) defined informational privacy as:
Control over when, how, and to what extent information is communicated.
• This definition is especially relevant to the Web.
• Most modern privacy violations involve loss of control over personal data.

Personal, Private, and Personally Identifiable Information


Types of Information
• Personal information
o Name, birth date, education, family.
• Private information
o Personal information not generally known.
o Some protected by law (education records, bank records).
o Privacy depends on context.

Web Security By [Link] - 2-


• Personally identifiable information (PII)
o Data that reveals identity (name, account number).
• Anonymized information
o Modified so identities cannot be discerned.
• Aggregate information
o Statistical summaries (e.g., Census tract data).

Triangulation
• Combining anonymized or aggregate data can reveal identities.
• Example: Zip code + birthday can uniquely identify individuals.
• Even “aggregate” questions may request PII unintentionally.

User-Provided Information
• Users often provide:
o Name, address, credit card details
o Email addresses and phone numbers
• Merchants store data in user accounts with usernames/passwords.
• Security questions (e.g., mother’s maiden name) are used for password recovery.
• Figures 8-1 and 8-2 illustrate:
o Registration forms
o Account information collection processes
• U.S. law places few restrictions on how websites use collected data.
• Privacy policies are voluntary.

Web Security By [Link] - 3-


Figure 8-1. By far, the greatest kind of personal information on the Web today is the
information provided by consumers when they register at web sites.

Web Security By [Link] - 4-


Figure 8-2. Disney’s registration page for adults asks for name, email address, gender, and
birthday, in addition to mailing address. Many people are surprised how identifying even
simple demographic information can be. For example, in many cases a person can be uniquely
identified by day of birth (without the year) and Zip code.
Log Files
• Log files record network and user activity.
• Created for:
o Debugging
o Maintenance
o Marketing
o Government investigations
• Users generally cannot know what is logged.

Retention and Rotation

Web Security By [Link] - 5-


• Rotation: automatic deletion of old logs.
• Some systems retain logs until manually deleted.
• Backup systems (e.g., magnetic tape) may preserve logs for years.
• Example web server logs show:
o access_log
o access_log.1
o access_log.[Link]
• These indicate compressed and rotated logs.

Web Logs
• Each page request generates entries on:
o Web servers
o Databases
o Firewalls
o Proxies
• Logs can be subpoenaed or misused.
• Most logs are never reviewed, yet store extensive data.

What’s in a Web Log?


• IP address and hostname
• Timestamp
• Requested URL
• Browser type
• Refer link
• Errors
• Authentication usernames
• Logs can be cross-correlated to identify users.
Example 8-1
• Shows a typical web server log
• Demonstrates:
o IP tracking
o Browser identification
o Refer links

Web Security By [Link] - 6-


The Refer Link Field
• Automatically sends the previous URL.
• Used to:
o Measure advertisement effectiveness
o Track navigation paths
• Can leak:
o Search queries
o Form data
• GET vs POST:
o GET embeds data in URLs → higher privacy risk

Obscuring Web Logs


• Proxy servers hide user IP addresses.
• Proxies do not guarantee anonymity.
• Proxy logs can still identify users.

Web Security By [Link] - 7-


RADIUS Logs
• RADIUS authenticates dial-up users.
• Logs include:
o Username
o IP address
o Session time
o CALLER-ID
• Played a key role in identifying the Melissa worm author.

Mail Logs
• Track:
o Sender and recipient
o Time
o Message ID
• Content usually not logged.
• Useful for identifying:
o Communication patterns
o Mailing list membership

DNS Logs
• DNS servers can log every query.
• Reveal:
o Websites accessed
o User behavior patterns
• Useful for maintenance and surveillance.

Understanding Cookies
• Cookies are ASCII text blocks stored by browsers.
• Sent automatically with each request.
• Introduced by Netscape Navigator 2.0.
• Used to maintain state across HTTP sessions.

The Cookie Protocol


• Cookies are set using Set-Cookie headers.
• Key attributes:
o expires
o domain
o path
o secure
• Cookies are sent back via HTTP headers.
Example Cookies
• HotBot sends multiple cookies (Table 8-1).
• Includes third-party cookies (e.g., .[Link]).
• Cookies used for:

Web Security By [Link] - 8-


o Tracking
o Visitor counting
o Advertising profiles

Cookie Uses
• Store user data directly
• Or store identifiers linked to databases
• Widely used for advertising analytics

Cookies and Privacy


• Cookies can:
o Weaken privacy (profiling, tracking)
o Improve privacy (store preferences locally)
• Example privacy-protecting cookie:
o DigiCrime virus counter

Cookie Jars
• Cookies stored:
o In memory
o On disk if persistent
• Netscape:
o [Link] (Example 8-2)
• Internet Explorer:
o Individual files (Figure 8-3, Example 8-3)

Web Security By [Link] - 9-


Cookie Security
• Cookies can be edited by users.
• Secure cookies use:
o Random IDs
o Cryptographic MACs
• Examples compare insecure vs more secure cookies.
• Chapter 16 discusses secure cookie creation.

Web Security By [Link] - 10-


Disabling Cookies
• Browsers allow:
o Accept all
o Reject all
o Prompt user
• Cookies already accepted cannot be selectively blocked.
• Advanced techniques include:
o File permission tricks
o Proxy filters
• Figure 8-4 shows cookie management interface.

Web Bugs
• Introduced publicly in 2000 by the Privacy Foundation.
• Small invisible images (1×1 GIF).
• Also called:
o Clear GIFs
o Beacon GIFs

Web Bugs on Web Pages


• Example bugs from [Link]:
o Doubleclick
o MatchLogic
• Enable third-party tracking without ads.
• Allow cross-database correlation.
• Figure 8-5 shows web bug in Yahoo Profile.

Web Security By [Link] - 11-


Figure 8-5. A Yahoo profile that was bugged with a web bug by the Privacy Foundation

Web Bugs in Email Messages and Word Files


• Used to detect:
o Email reading
o Forwarding
• Can be embedded in:
o HTML email
o Usenet messages
o Microsoft Word documents

Uses of Web Bugs


• Usage statistics
• Cross-site tracking
• User profiling
• Cookie synchronization
• Ad verification

Web Security By [Link] - 12-


• Email tracking
• Detecting copyright infringement

2. Privacy-Protecting Techniques
• The Internet allows extensive collection of personal information.
• This chapter focuses on practical techniques to protect privacy.
• Techniques are mostly:
o Simple
o Common-sense
o Immediately applicable
• Key areas covered:
o Choosing a good service provider
o Using strong passwords
o Cleaning online traces
o Avoiding spam and junk email
o Protecting against identity theft
• Chapter 10 discusses software-based privacy tools.
• Legal aspects of privacy are discussed in Chapter 24.

Choosing a Good Service Provider


• The most important privacy decision is selecting a trustworthy ISP.
• ISPs can monitor:
o Every website visited
o Emails sent and received
o Online behavior patterns
• Dial-up ISPs can infer:
o When you are home
o Travel or vacation periods
• ISPs may learn:
o Workplace location (via email access)
o User demographics
ISP Monitoring Practices
• Some ISPs:
o Monitor activity for maintenance and research
o Sell browsing data for revenue
• Monitoring may be:
o Clearly disclosed
o Or done silently
• New equipment allows ISPs to:
o Monitor ads downloaded
o Replace advertisements
o Generate user-level statistics

Web Security By [Link] - 13-


ISP Privacy Policies
• Some ISPs enforce strict data-access rules.
• Others have no privacy policies.
• Many policies state:
o “We can monitor anything we want.”
• Privacy policies may use vague legal language.
• Some ISPs provide no privacy policy at all.
• Legal protections are limited; ISPs hold significant power.

Picking a Great Password


• Passwords are the simplest form of authentication.
• A password is a shared secret between user and computer.
• Strong passwords are a first line of privacy defense.
• Risks:
o Easy-to-guess passwords
o Reusing passwords across services

Why Use Passwords?


• Early personal computers:
o Used by one person
o Rarely required passwords
• Internet use introduced:
o Email account passwords
o Website account passwords
• Passwords prevent:
o Unauthorized access
o Viewing personal data
• Modern operating systems:
o Windows
o Macintosh
o Unix
• Passwords control limited access to personal data.
• Users often receive poor guidance on password selection.

Bad Passwords: Open Doors


• Bad passwords are easy to guess.
• Crackers use:
o Automated password-guessing programs
o Lists of common passwords
• Weak passwords include:
o Names (self, family, pets)
o Dictionary words
o Short passwords
o Common substitutions (l → 1, E → 3)

Web Security By [Link] - 14-


o Words backwards
• Examples of weak choices:
o Movie characters
o Landmarks
o Phone numbers
o Famous computer scientists
• Web-based services are more vulnerable due to:
o High-speed guessing attempts
• Password rules vary widely across services.

Smoking Joes
• “Joe accounts”:
o Username and password are identical
• Extremely easy for attackers to exploit.
• Crackers often check for Joe accounts first.
• Making username lists public increases risk.

Good Passwords: Locked Doors


• Strong passwords:
o Use uppercase and lowercase letters
o Include digits and punctuation
o Are at least 7–8 characters long
o Are easy to remember
o Can be typed quickly
• Suggested techniques:
o Combine words with symbols (robot4my)
o Use personal acronyms
• Once published, examples become bad passwords.

Bad Passwords
• Avoid:
o Names (yours or others’)
o Birthdates
o Social Security numbers
o Usernames
o Dictionary words
o Keyboard patterns (qwerty)
o Single-digit variations
• Eight-character random passwords provide:
o Billions of combinations
o Protection against brute-force attacks
• Longer passwords often fail due to:
o System truncation at 8 characters

Web Security By [Link] - 15-


Writing Down Passwords
• Written passwords can be stolen.
• However:
o A complex written password may be safer than a weak memorized one.
• If writing down passwords:
o Do not label them as passwords
o Do not include account names
o Do not attach to computer
o Disguise or scramble them
• Password-keeping programs (Table 9-1) can help.

Strategies for Managing Multiple Usernames and Passwords


• Reusing passwords increases risk:
o One breach compromises many accounts
• System administrators may access stored passwords.
• Password restrictions differ by system.
Password Classes
• Divide passwords by security level:
o Banking
o Email
o Low-security sites
Password Bases
• Modify a base password per service.
• Avoid obvious patterns.
Password Rotation
• Change passwords periodically.
• Can become confusing over time.
Password Keepers
• Store passwords securely in encrypted form.
• Built into browsers (Netscape, Internet Explorer).
• Available as:
o Wallet programs
o Stand-alone software
• PGP can be used to create a custom password safe.

Web Security By [Link] - 16-


Sharing Passwords
• Sharing passwords gives others:
o Access to personal data
o Ability to impersonate you
• Treat passwords like house keys.
• Best practices:
o Share discreetly
o Never email plaintext passwords
o Change passwords after sharing ends

Resist Social Engineering Attacks


• Attackers trick users into revealing passwords.
• Common methods:
o Fake ISP emails
o Phone calls posing as IT staff
o Requests to reset passwords
• Attacks succeed due to:
o Desire to be helpful
o Lack of security awareness

Beware of Password Sniffers and Stealers


Password Sniffers
• Capture unencrypted passwords in transit.
• Target protocols:
o FTP
o HTTP
o POP
o TELNET
o RLOGIN
• Sniffers have been found on:
o University networks
o Corporate systems
o ISP backbones
• Use encrypted protocols to reduce risk.

Keystroke Recorders and Keyboard Sniffers


• Record everything typed.
• Can be:
o Software-based
o Hardware-based
• Figure 9-1: KeyKatch device
o Small hardware keystroke recorder
o Undetectable without physical inspection
• Screen recorders capture display content.

Web Security By [Link] - 17-


• Programs like Back Orifice 2000 enable remote spying.

Beware of Public Terminals


• Higher risk of spyware.
• Precautions:
o Avoid confidential access
o Use temporary webmail accounts

Cleaning Up After Yourself


• Internet use leaves electronic footprints.
• Computer forensics can reveal:
o Visited websites
o Downloaded data
• Cleanup reduces privacy risk.
• Automatic cleanup tools discussed in Chapter 10.

Browser Cache
• Cache stores previously visited pages.
• Improves speed but reduces privacy.
• Privacy protection methods:
o Disable caching for SSL pages
o Disable caching entirely
o Manually delete cache

Managing Your Cache with Internet Explorer


• Use Internet Properties panel.
• Options:
o Delete Files
o View cached files
• Figure 9-2: Internet Properties panel
• Figure 9-3: Cache directory view
• Figure 9-4: ActiveX objects list

Web Security By [Link] - 18-


Web Security By [Link] - 19-
Managing Your Cache with Netscape Navigator
• Preferences → Advanced → Cache
• Clear disk and memory cache
• Figure 9-5: Netscape cache settings

Web Security By [Link] - 20-


Cookies
• Cookies store session and tracking data.
• Can expose personal information.
Crushing Internet Explorer’s Cookies
• Cookies stored in History directory.
• Can be manually deleted.
Crushing Netscape’s Cookies
• Stored in [Link].
• Managed via Cookie Manager.
• Figure 9-6: Cookie Manager menu
• Figure 9-7: Stored cookies view

Web Security By [Link] - 21-


Browser History
• Browsers store visited URLs.
• Can reveal sensitive activity.
• Clearing history is recommended.
Clearing Internet Explorer’s Browser History
• Stored in [Link].
• Viewed as databases in Explorer.
• Figure 9-8: History database view
• Figure 9-9: Typed URLs registry

Web Security By [Link] - 22-


Clearing Netscape Navigator’s Browser History
• Preferences → Navigator → History

Passwords, Form-Filling, and AutoComplete Settings


• Browsers store:
o Form data
o Usernames
o Passwords
• Convenient but risky.
• Figure 9-10: AutoComplete prompt

Web Security By [Link] - 23-


Clearing AutoComplete with Internet Explorer
• Content tab → AutoComplete
• Clear forms and passwords
• Figure 9-11: AutoComplete settings

Web Security By [Link] - 24-


Clearing Sensitive Information with Netscape Navigator
• Password Manager
• Figure 9-12: Clear sensitive information

Avoiding Spam and Junk Email


• Spam is a major privacy concern.

Web Security By [Link] - 25-


• Causes:
o Time loss
o Privacy invasion
o ISP customer loss

Protect Your Email Address


• Avoid publishing email addresses.
• Remove listings from online directories.
• Avoid posting to:
o Mailing lists
o Usenet
• Choose uncommon usernames.

Use Address Munging


• Modify email addresses to confuse spam bots.
• Prefer mangling domain names.

Use an Antispam Service or Software


• Antispam services:
o Filter messages externally
o Use whitelists
• Examples:
o BrightMail
o SpamCop
• Antispam software:
o Runs locally
o Requires maintenance
• Examples:
o SpammerSlammer
o Spam Exterminator

Identity Theft
• Identity theft involves misuse of personal data.
• Example: Stephen Shaw case
• Consequences:
o Financial loss
o Credit damage
o Emotional distress
o Employment difficulties
• Often takes years to resolve.
• Common methods:
o Stolen credit reports
o Trash rummaging
o Phishing scams

Web Security By [Link] - 26-


Protecting Yourself From Identity Theft
• Identity theft thrives due to weak identity verification.
• Consumers can take preventive steps.
Shred Your Trash
• Use strip or cross-cut shredders.
• Shred documents with personal data.
Monitor Your Credit Report
• Regularly check reports from:
o Equifax
o Experian
o TransUnion
• Consider monitoring services.
Be Careful of Wallet Contents
• Do not carry:
o Social Security card
o Birth certificate
• Photocopy cards for records.
Cancel Unnecessary Credit Cards
• Reduce exposure.
Avoid Using SSNs as Account Numbers
• Request alternate identifiers.
Separate Online and Offline Credit Cards
• Use virtual card numbers when possible.
Don’t Give Personal Information to Callers
• Verify identity of callers.
Use Passwords on Accounts
• Replace “mother’s maiden name” with passwords.

If You Are the Victim of Identity Theft


• Report to:
o Police
o Secret Service
o Postal Inspector
• Contact:
o FTC Identity Theft Hotline
o Banks and credit card companies
• Obtain and dispute all credit reports.
• Consider legal assistance.

3. Privacy-Protecting Technologies
• This chapter introduces privacy-protecting technologies used while browsing the
Web.

Web Security By [Link] - 27-


• These technologies help safeguard personal information from advertisers, trackers,
and unauthorized access.
• The chapter is organized by program categories, including:
o Blocking ads
o Crushing cookies
o Anonymous browsing
o Secure email
• For each category:
o The basic concept is explained
o Examples of programs are given
o One or two programs are demonstrated
• Because the Internet changes rapidly:
o Some programs may no longer exist
o New programs may not be listed
• The chapter should be treated as a survey of tools, not a buyer’s guide.

Blocking Ads and Crushing Cookies


• Web browsers are increasingly designed to deliver advertisements.
• Major browser companies (Microsoft, Netscape, Opera) profit from advertising.
• Figure 10-1: Shows browsers functioning as ad-delivery platforms.
• Unlike traditional advertising:
o Internet ads can track users
o Personal data can be collected and correlated
• Advertisers can:
o Track browsing behavior
o Build detailed user profiles
• The Internet’s design also allows users to:
o Defend against cookies
o Block advertisements

Web Security By [Link] - 28-


Local HTTP Proxies
• Proxy servers relay requests between browsers and web servers.
• Commonly used in corporate firewalls.
• A local HTTP proxy:
o Runs on the user’s own computer
o Proxies HTTP (web) traffic
• Figure 10-2: Shows a local HTTP proxy between the user and the Web.
• Because of its position, a local proxy can:
o Monitor browsing activity
o Preview web pages
o Modify web content

Web Security By [Link] - 29-


Capabilities of a Local HTTP Proxy
• Record all visited web pages
• Block or allow access to specific sites
• Insert or remove cookies
• Edit HTML content
• Modify downloaded images
• If controlled by the user:
o Becomes a powerful privacy tool
• If controlled by others:
o Can be invasive and dangerous

Using Ad Blockers
• Ad blockers often use local HTTP proxies.
• Two main ad-blocking methods:
o Blocking ad-related URLs
o Editing HTML to remove ads
• Figures 10-3, 10-4, 10-5: Demonstrate ad blocking and HTML modification.

Web Security By [Link] - 30-


Web Security By [Link] - 31-
Web Security By [Link] - 32-
Reasons to Block Advertisements
• Ads are distracting
• Ads waste screen space
• Ads slow down page loading
• Ads often contain tracking technologies (cookies)

Disadvantages of Blocking Ads


• Some ads contain useful information
• Many websites rely on ad revenue
• Blocking ads may harm free content availability

Crushing Cookies
• Many ad blockers also crush cookies.
• Selective cookie blocking allows:

Web Security By [Link] - 33-


o Blocking cookies from advertisers
o Allowing cookies from trusted sites (banks, brokers)
• This balances privacy and functionality.

Additional Features of Ad Blockers


• Remove background music and images
• Disable JavaScript, Java, and ActiveX
• Stop animated GIFs
• Block pop-ups
• Prevent browser history manipulation
• Disable auto-refresh pages
• Block refer links
• Ad blockers can block dozens of ads after only a few pages.
• Table 10-1: Lists available ad-blocking programs.
• Most ad blockers:
o Run on Windows
o Some can protect entire local networks

Anonymous Browsing
• HTTP proxies cannot hide IP addresses.
• IP addresses:
o Contain personal information
o Allow tracking across websites
• IPs can be used to identify users via logs and legal orders.

Web Security By [Link] - 34-


Examples of IP Address Tracking
• MIT Media Lab hostname:
o Linked directly to a single user
• Media One cable modem hostname:
o Linked via ISP records
• WebTV proxy server:
o Shared among many users
o Logs still exist
• Dial-up server hostnames:
o Reassigned over time
o Usage records retained
IP Addresses in Email
• Web-based email often includes IP addresses in headers
• Example shown using Hotmail headers
• IP leakage may reveal location and identity

Simple Approaches to Protecting Your IP Address


Browse from a Public Terminal
• Public libraries and universities offer anonymity
• Institutions are often committed to user privacy
Use America Online
• AOL uses caching proxy servers
• User IP is hidden behind proxy names
• Example proxy hostnames listed
• Privacy depends on AOL policies and legal pressure
Use Your ISP’s Web Cache or Proxy Server
• ISP proxies mask end-user IPs
• Remote servers see the proxy IP instead of the user’s

Anonymous Web Browsing Services


• Provide stronger anonymity than simple methods
• Operate as proxy services
• Figure 10-6: Shows anonymous proxy architecture
• Key feature:
o No log files kept
• Cannot comply with court orders for user activity

Web Security By [Link] - 35-


[Link]
• One of the first anonymous browsing services
• Requires:
o No software installation
o No browser reconfiguration
• Users enter URLs on the Anonymizer website
• URLs are rewritten to maintain anonymity
• Example HTML rewriting shown
• Figure 10-7: Web page viewed through Anonymizer
• Offers:
o Free ad-supported service
o Paid service (~$5/month in 2001)
o Secure encrypted tunnel option

Web Security By [Link] - 36-


Freedom, by Zero Knowledge Systems
• Uses multiple proxy servers across countries
• Figure 10-8: Shows multi-hop encrypted routing
• Each packet:
o Encrypted in multiple layers
o Decrypted step-by-step by different servers
• Offers:
o Anonymous browsing
o Anonymous chat
o Untraceable encrypted email
• Supports multiple identities (nyms)
• Each nym can:
o Use separate cookies
o Block cookies
• Cost: $49.95/year (includes 5 nyms)

Web Security By [Link] - 37-


safeWeb
• Similar to Anonymizer
• Key features:
o Free service
o SSL encryption
o Customization options
• Supported by non-tracking ads
• Figure 10-9: safeWeb interface

Web Security By [Link] - 38-


Secure Email
• Email often carries highly sensitive information
• Standard email lacks security
• Threats include:
o Identity leakage
o ISP or employer monitoring
o Misdelivery
o Unauthorized access
o Forwarding without consent
o Message tampering
• These are real, experienced risks
• Can be mitigated using proper technologies

Hotmail, Yahoo Mail, and Other Web-Based Email Services


• Provide:
o Free or low-cost email
o Access from anywhere
• Useful for:
o Semi-permanent addresses
o Anonymous use with anonymous browsing
• Risks include:
o Provider access to all emails
o No end-to-end encryption
o Exposure to subpoenas
o Interception without SSL

Web Security By [Link] - 39-


o Advertisements added to messages
• Useful for disposable or single-purpose email accounts

Hushmail
• Secure web-based email service
• Figure 10-10: Hushmail interface
• Encrypts messages so:
o Even Hushmail staff cannot read them
• Encryption occurs on the user’s computer
• Figure 10-11: Client-side encryption process
• Uses public-key cryptography
• Private key protected by user passphrase
• If passphrase is forgotten:
o Account is unrecoverable
• Messages:
o Automatically encrypted and decrypted
o Not stored unencrypted on servers or disks
• Offers:
o Free ad-supported version
o Premium paid version

Web Security By [Link] - 40-


Web Security By [Link] - 41-
Omniva’s Self-Destructing Email
• Email copies exist in many locations
• Figure 10-12: Shows multiple email copies
• Email archives are valuable in:
o Investigations
o Litigation
• Omniva uses time-limited cryptographic access
• Sender chooses message expiration date
• Figure 10-13: Encryption and key distribution
• Encrypted messages are unreadable without keys
• Figure 10-14 & 10-15: Key-based access and expiration
• After expiration:
o Key is deleted
o Message becomes unreadable
• Does not prevent:
o Printing
o Manual copying
• Improves privacy and reduces long-term exposure

Web Security By [Link] - 42-


Web Security By [Link] - 43-
Web Security By [Link] - 44-
4. Backups and Antitheft
• Focuses on:
o Data loss
o Theft
o System recovery
• Threats include:
o Hardware failure
o Theft
o Disasters
o Human error

Using Backups to Protect Your Data


• Backups are copies of important data
• Can be:
o Simple (Zip disk)
o Complex (tape + restore floppy)
• Allow system restoration after loss

Make Backups!
• Failures are unpredictable
• Backups prevent permanent data loss
• Insurance replaces hardware, not data
• Essential for recovery after disasters

Why Make Backups?


Reasons
• Archival records
• User error
• System-staff error
• Hardware failure
• Software corruption
• Electronic break-ins
• Theft
• Natural and human-made disasters

What Should You Back Up?


• Two strategies:
1. Back up only unique data
2. Back up everything
• Recommended: Back up everything
• Simplifies restoration
• Protects against missing installation media

Web Security By [Link] - 45-


Types of Backups
Level-Zero Backup
• Initial full system backup
Full Backup
• Copies all files regularly
Incremental Backup
• Copies only changed files
• Common strategy:
o Full backup biweekly
o Incremental backup nightly
• Figure 11-1: Rotating backup tapes

Guarding Against Media Failure


• Use tandem backup sets (A and B)
• Protects against tape failure
• Periodically test restores
• Annual full restoration recommended

Security for Backups


Physical Security
• Remove media from drives
• Store backups off-site
• Use media-safe fireproof storage
Data Security
• Backups contain all data
• Encrypt backups

Web Security By [Link] - 46-


• Secure encryption keys
• Use escrow or shared key systems

Legal Issues
• Backup tapes may be subpoenaed
• Retention policies should apply to backups
• Segregate sensitive data
• Back up carefully

Preventing Theft
• Theft often occurs due to opportunity
• Prevention reduces risk significantly

Locks
• Laptops include security slots
• Figure 11-2: Laptop lock slot
• Cable locks prevent grab-and-run theft
• Vendors: Kensington, Kryptonite

Tagging
• Equipment tags deter resale
• Figure 11-3: STOP theft tag
• Tags:
o Are serial-numbered
o Leave permanent marks if removed
• Used by governments and universities

Web Security By [Link] - 47-


Laptop Recovery Software and Services
• Tracing software reports location
• Example: Computrace
• Cost-effective
• Works unless disk is reformatted

Awareness
• Simple habits reduce theft:
o Never leave laptops unattended
o Secure laptops in hotels
o Carry laptops personally
o Avoid window-side placement

Web Server Security


1. Physical Security for Servers
• Physical security includes all protective measures before logical access (typing
commands).
• Examples:
o Alarm systems alerting police during break-ins.
o Key locks on power supplies to prevent unauthorized shutdown.
o Locked computer rooms with closed-circuit cameras.
o Uninterruptable Power Supplies (UPS) and power conditioners to protect
against power grid issues.
• Importance:
o Even strong encryption and firewalls fail if physical access is compromised.
o Example: janitor stealing unattended laptop/server → total security breach.

Planning for the Forgotten Threats


• Physical security is often undervalued by organizations.
• Case studies:
o Investment firm secured daytime access but ignored night cleaning staff.
o Magazine lost $100,000+ in computers due to insider misuse of key cards.
• Catastrophic events (e.g., September 11, 2001) show limits of physical security.

Web Security By [Link] - 48-


• Key lesson:
o Catastrophic risks should not prevent disaster planning.
o Organizations with off-site mirror facilities recovered fastest.
• Challenges:
o Physical security varies by site.
o Cannot be preinstalled, downloaded, or sold as software.
• Goal of discussion:
o Provide starting points, not fixed solutions.

The Physical Security Plan


• First step: create a written physical security plan.
• Should be:
o Part of written security policy.
o Reviewed by experts.
o Approved by senior management.
• Purpose:
o Planning + political/organizational buy-in.

Security Plan Should Include:


• Physical assets being protected.
• Locations of assets.
• Security perimeter and its weaknesses.
• Threats (attacks, accidents, natural disasters).
• Existing defenses and improvements.
• Cost estimates.
• Value of protected information.
• Sensitive document → contains weakest defense points.
• Smaller setups still benefit from basic planning.

Five Key Questions:


1. Who has physical access?
2. What if access is abused violently?
3. What if competitors enter unnoticed?
4. What if fire destroys systems?
5. How will users react after a disaster?

The Disaster Recovery Plan:


• Definition: plan to restore systems after theft or damage.
• Recommendations:
o Rapid acquisition of replacement equipment.
o Regular testing of backup restoration.
• Vendor systems can be borrowed for testing.
• Ensure secure disk wiping before returning borrowed systems.

Web Security By [Link] - 49-


Other Contingencies
• Loss of phone/network service.
• Vendor continuity and support.
• Staff absenteeism.
• Death/incapacitation of key personnel.
• Emphasis on organizational resilience.

Protecting Computer Hardware


• Computers are:
o Valuable like jewelry.
o Frequently accessed like office equipment.
• Greatest loss = data, not hardware.
• Risks:
o No backup or stolen backups.
o Time required to rebuild systems.
o Legal, financial, and reputational damage.
• Power sensitivity:
o Vulnerable to surges from lightning or appliances (vacuum cleaner example).

The Environment
• Fire
• Smoke
• Dust
• Earthquake
• Explosion
• Temperature Extremes
• Bugs (biological)
• Electrical Noise
• Lightning
• Vibration
• Humidity
• Water
• Environmental Monitoring
Fire
• Fire damage sources:
o Flames, heat, water.
• Fire suppression:
o Gas-charged systems (nitrogen, argon, CO₂).
o Loud alarms before discharge.
• Guidelines:
o Hand-held extinguishers near exits.
o Annual fire extinguisher training.
o Monthly extinguisher checks.

Web Security By [Link] - 50-


o Override false alarms.
o Emergency phone access.
• Sprinkler systems:
o Computers may survive if power is cut.
o Dry-pipe systems preferred.
• Water recovery:
o Dry equipment fully.
o Clean circuit boards if minerals present.
• Modern guidance:
o Water sprinklers may outperform gas systems.

Smoke
• Smoke damage:
o Abrasive particles cause disk crashes.
o Toxic smoke from electrical fires (e.g., video monitors).
• Tobacco smoke:
o Harms people and computers.
o Causes keyboard failure.
• Guidelines:
o No smoking.
o Smoke detectors above/below floors and ceilings.

Dust
• Dust effects:
o Abrasive, conductive.
o Causes shorts and erratic behavior.
• Guidelines:
o Dust-free rooms.
o Clean air filters.
o Use HEPA/ULPA vacuums.
o Keyboard dust covers (avoid overheating/static).

Earthquake
• Earthquake risk is widespread.
• Historical examples:
o San Francisco (1906), New Madrid fault.
• Guidelines:
o Avoid high surfaces.
o Secure shelves.
o Place computers under strong tables.
o Avoid windows.
o Bolt/tie computers (also deters theft).

Web Security By [Link] - 51-


Explosion
• Risks from gas or solvents.
• Guidelines:
o Store solvents safely.
o Off-site backups.
o Keep systems away from windows.
o Use ruggedized systems if needed.

Temperature Extremes
• Optimal range: 50–90°F (10–32°C).
• Risks:
o Overheating damages components.
o Cold causes thermal shock.
• Guidelines:
o Temperature alarms.
o Adequate airflow (6–12 inches).
o Allow transported systems to acclimate.

Bugs (biological)
• Origin of term “bug” (Grace Murray Hopper, Mark I).
• Insects damage:
o Power supplies.
o Wiring insulation.
• Prevent insect infestation.

Electrical Noise
• Sources:
o Motors, fans, transmitters.
• Electrical surges:
o Vacuum cleaner example.
• Guidelines:
o Isolated circuits.
o UPS and line filters.
o Static mats.
o Keep transmitters ≥5 feet away.

Lightning
• Causes magnetic and power surges.
• Guidelines:
o Unplug during storms.
o Keep backups away from steel structures.
o Avoid outdoor copper cabling.
o Use conduits for outdoor cables.

Web Security By [Link] - 52-


Vibration
• Effects:
o Loosened boards.
o Disk misalignment.
• Guidelines:
o Rubber/foam mats.
o Avoid placing printers on computers.
o Laptops are more vibration-resistant.

Humidity
• Benefits:
o Reduces static.
• Risks:
o Too dry → static damage.
o Too humid → condensation.
• Optimal: >20% RH, below dew point.
• Use humidity alarms if needed.

Water
• Dangers:
o Electrical shorts.
o Trace melting.
• Sources:
o Flooding, sprinklers, plumbing failures.
• Guidelines:
o Water sensors at multiple heights.
o Avoid basements.
o Automatic power cutoffs.

Environmental Monitoring
• Continuous monitoring of temperature and humidity.
• One recorder per 1,000 sq ft.
• Regular log review.

Preventing Accidents
Food and Drink
• Liquids destroy keyboards and consoles.
• Food oils damage media and screens.
• Rule: No food or drink near computers.

Physical Access
Raised floors and dropped ceilings
• Intruders can bypass locked rooms.

Web Security By [Link] - 53-


• Guidelines:
o Walls must extend above ceilings and below floors.

Entrance through air ducts


• Large ducts enable entry.
• Guidelines:
o Small ducts.
o Welded screens.
o Motion detectors (paranoid option).

Glass walls
• Risks:
o Easy breakage.
o Shoulder surfing.
• Guidelines:
o Avoid glass.
o Use translucent blocks.
o Useful for guarded areas.

Vandalism
• Motivations:
o Revenge, politics, riots, entertainment.
• Often fast and destructive.
Ventilation holes
• MIT case: Coca-Cola poured into vents.
• Prevention:
o No food/drink.
o Guards or CCTV.

Network cables
• Vulnerable to cuts.
• Fiber optics:
o Harder to repair, attractive targets.
• Protection:
o Steel conduits.
o Shielded, pressurized conduits.
• Redundancy alone is insufficient.

Network connectors
• High-voltage attacks possible.
• Example:
o Thin-wire Ethernet plugged into 110VAC outlet.

Web Security By [Link] - 54-


Defending Against Acts of War and Terrorism
• Non-military systems are targets.
• High-risk sectors need extra protection.
• Best defense:
o Hot backups
o Mirrored disks
o Geographically distributed servers

Preventing Theft
Physically secure your computer
• Tie-down devices deter theft.

RAM theft
• Common and hard to detect.
• Figure 14-1:
o Illustrates RAM modules being removed from a computer.
• Symptoms:
o Slower performance.
• RAM and CPU chips are high-value items.

Encryption
• Stolen systems expose data.
• Encryption makes stolen data useless.
• Strong encryption recommended for all sensitive data.

Laptops and portable computers


• High theft risk (especially airports).
• Prevention:
o Engraving ownership details.
o Property tags.
• Figure 11-3:

Web Security By [Link] - 55-


o Shows Secure Tracking of Office Property tag.
• Encryption tools:
o Windows 2000 Encrypted File System.
o PGP Disk.
• Competitive intelligence often targets laptops.

Protecting Your Data


There is a close relationship between physical security of computer systems and the privacy,
integrity, and availability of data. If a computer system is stolen or physically compromised,
the data it contains is also at risk. Many attacks on data bypass physical safeguards entirely.
This section discusses various data attacks and countermeasures, reinforcing earlier security
concepts from a data-centric perspective.
Eavesdropping
Electronic eavesdropping is one of the most dangerous forms of data piracy. With relatively
simple equipment, an attacker can record:
• Every keystroke
• Information displayed on the screen
• Data sent to printers
The victim is typically unaware of the attack, unknowingly exposing:
• Sensitive information
• Passwords
• Operational procedures
In many cases, detection occurs only after the stolen data is misused, by which time serious
damage has already occurred. Although eavesdropping cannot always be detected, careful
security practices can reduce the risk.
Protection Against Eavesdropping
• Encryption is the most effective defense.
• Assume communications are being monitored.
• Encrypt all data transmissions by default.

Wiretapping
Wiretapping exploits the fact that electrical wires can easily leak information. Attackers can:
• Splice directly into cables
• Use induction loops without physical contact

Web Security By [Link] - 56-


• Monitor telephone lines, modems, and RS-232 communications
• Intercept LAN traffic
Advanced intelligence agencies can even monitor underwater fiber-optic cables by
analyzing emissions from amplifiers and repeaters.

Guidelines for Preventing Wiretapping


• Regularly inspect data-carrying wires for damage
• Use shielded or armored cables
• Route cables through steel conduits
• In high-security environments:
o Pressurize conduits with gas
o Use pressure sensors to detect tampering
(These methods are expensive to implement and maintain.)

Eavesdropping over Local Area Networks (Ethernet and twisted pair)


Ethernet and twisted-pair LANs are highly vulnerable. An attacker can intercept traffic by:
• Connecting a packet monitor to an unused network port
Security Measures
• Disable unused Ethernet ports in wiring closets
• Do not leave live network ports in unused offices
Role of Switches
• Ethernet switches limit packet broadcasting
• Improve security over shared Ethernet
• However, skilled attackers can still monitor switched networks
• Switches should not be relied upon as the sole security mechanism
Network Monitoring
• Periodically scan for unauthorized hosts
• Monitor unknown MAC addresses
• Configure hubs/switches to:
o Raise alarms
o Disable ports on MAC/IP mismatch
• Use MAC address filtering and port lock-down

Eavesdropping on 802.11 Wireless LANs


Wireless LANs are inherently insecure.
• WEP encryption is weak
• Attackers can impersonate authorized users
• Wireless traffic is easily intercepted
Protection Measures
• Avoid wireless LANs in high-security environments
• If required:
o Place access points outside the firewall
o Use additional encryption (VPN or SSL)

Web Security By [Link] - 57-


Eavesdropping by Radio and Using TEMPEST
All electronic equipment emits radio frequency (RF) radiation.
• Emissions can be analyzed to reconstruct processed data
• Known as radio eavesdropping
TEMPEST
• A certification system measuring susceptibility to RF monitoring
• TEMPEST-certified equipment:
o Better shielding
o Larger and more expensive
Alternative Approaches
• TEMPEST-certified rooms or buildings
• Conductive shielding in walls
• Reduction of monitor emissions using special fonts (e.g., Soft TEMPEST)
Although not a concern for most users, radio eavesdropping is easier than expected and
should not be ignored.

Fiber Optic Cable


Fiber optic cable offers improved protection:
• Harder to tap than copper cable
• Tapping usually requires cutting the cable
• Less interference and grounding issues

Limitations:
• Optical “vampire” taps exist
• Fiber is fragile
• Repairs are difficult

Keyboard Monitors
Keyboard monitors are hardware devices placed between the keyboard and computer.
• Capture every keystroke
• Undetectable by software
• Require physical access to retrieve data
• Typically inexpensive and widely available

Protecting Backups
Backup media is highly vulnerable.
• OS security protections do not apply to tapes
• Anyone with physical access can read backup data
Backup Protection Guidelines
• Never leave backups unattended
• Use bonded messengers
• Sanitize old backup media
• Encrypt backups
• Secure cryptographic keys carefully

Web Security By [Link] - 58-


Verify Your Backups
Backups degrade over time due to:
• Environmental conditions
• Magnetic print-through
Best Practices
• Test recent and archived backups
• Periodically restore sample backups
• Spin and rewind tapes annually to reduce print-through
• Verify backups at least once per year

Protect Your Backups


• Backups face the same hazards as live systems
• Store backups at a separate physical location
• Geographic separation improves survivability

Sanitizing Media Before Disposal


Deleting files does not erase data.
• Data remnants remain recoverable
Hard Disk Challenges
• Hidden and reserved disk storage
• Requires disk-specific sanitization software
• Risk of firmware-level attacks
Tape and Optical Media
• Use bulk erasers for tapes
• Overwrite multiple times:
o Zeros
o Ones
o Random data
• Physical destruction may still be required

Sanitizing Printed Media


Printed materials often contain sensitive information:
• Source code
• Design documents
• Phone books
• System configurations
Improper disposal enables:
• Social engineering
• Corporate espionage
Dumpster Diving
• Attackers recover sensitive data from trash
• Can occur off-site after trash removal
Protection Measures
• Use shredders

Web Security By [Link] - 59-


• Train users on proper disposal
• Consider on-site incineration where permitted

Protecting Local Storage


Many devices store data unknowingly:
• Printers
• Fax machines
• Modems
• Terminals
These devices often lack:
• Password protection
• Encryption

Printer Buffers and Output


• Printers store documents in memory
• COPY buttons can reproduce sensitive data
• Network printers may contain hard disks
• Unclaimed printouts are vulnerable to theft

X Terminals
• May contain RAM or hard disks
• Often lack encryption
Security Guidelines
• Power off after use
• Password-protect storage
• Erase disks before servicing

Function Keys
• Can store keystroke sequences
• Storing passwords is dangerous
• Physical access compromises credentials

Unattended Terminals
Logged-in unattended systems allow:
• File theft
• Network attacks
• Identity misuse
Countermeasures
• Automatic logout
• Screen locking
• Shell autologout variables
• Secure screensavers

Web Security By [Link] - 60-


Key Switches
• Prevent booting into single-user mode
• Firmware passwords provide added security
• Physical access remains the primary risk

Personnel
People pose significant security risks.
• Insiders, contractors, and cleaning staff
• Inadequate background checks increase exposure
Controls
• Background investigations
• Bonding
• Security awareness training
• Incident response education

Story: A Failed Site Inspection


A company believed it had “nothing to lose,” yet a brief inspection revealed:
• Fire hazards
• Unprotected networks
• Poor access controls
• Theft opportunities
• Sabotage risks
Downtime costs were estimated at millions per hour, proving the organization had far more
to lose than expected.

2. Host Security for Servers


Host Security: Definition and Background
• Host security refers to the protection of the computer system on which a web
server runs.
• Historically treated as a standalone discipline within computer security.
• Extensive literature exists focusing on operating system and user-level protection.
Historical Context (1980s–Early 1990s)
• Host security was critical in multi-user time-sharing systems.
• Common environments:
o Universities: Preventing students from accessing each other’s coursework.
o Government systems: Segregating “Secret” and “Top Secret” information.
• Traditional concerns:
o Protecting the operating system from users
o Protecting users from each other
o Implementing auditing and monitoring mechanisms
Shift in the 1990s
• Rise of personal computers and distributed systems.
• False assumption: exclusive computer use reduced security needs.

Web Security By [Link] - 61-


• Reality:
o Distributed systems are equally or more vulnerable.
• Reasons for reduced emphasis:
o Increased complexity and cost of securing distributed environments.
o Preference for ease of deployment over security
Renewed Importance Due to the Web
• Web servers expose host systems to external attackers.
• If attackers gain OS-level control:
o They can access files
o Monitor communications
o Modify the web server itself
• Key principle: A compromised operating system cannot provide secure services.
Scope of Discussion
• No step-by-step guide provided due to constraints.
• Focus:
o Common host security problems
o Methods to minimize risks
• Additional references provided in Appendix E.

Current Host Security Problems


• Many issues identified in RFC 602 (1973) still exist.
• Common problems:
o Poor server hardening
o Weak or reused passwords
o Password sniffing using packet sniffers
• Motivations for attacks:
o Thrill-seeking
o Financial gain
o Ideological purposes
Dialup Access Issue
• Unauthorized dialups largely eliminated due to commercialization.
• New risk:
o Easily obtained “authorized” ISP trial accounts
• Threat has shifted from unauthorized users to misuse by authorized users.

A Taxonomy of Attacks
(Typically illustrated using attack flow diagrams or classification figures)
Unsecured Dialups
• Study by Peter Shipley found:
o Over 50,000 dialup modems
o More than 2% allowed unrestricted access
• Affected systems included:
o Fire departments
o Bookstore order-entry systems

Web Security By [Link] - 62-


o Medical records
• Attack methodology: systematic dialing (wardialing)
Remote exploits
• Allow compromise without logging in.
• Examples:
o Ping of Death (Windows NT 4.0 crash)
o BIND DNS remote root exploit
• Common technique:
o Buffer overflow
▪ Overwrites stack memory
▪ Executes attacker-supplied machine code
Malicious programs
• Back doors: Hidden access services
• Trojan horses: Appear legitimate but perform malicious actions
• Viruses:
o Modify existing programs
o Carry viral payloads
• Worms:
o Self-replicate over networks
o Install back doors or drop viruses

Stolen usernames and passwords and social engineering


• Attackers escalate normal user privileges to superuser/administrator.
• Use of stolen credentials to avoid traceability.
• Social engineering:
o Phone-based deception
o Pretending to be employees or service representatives
o Exploits human helpfulness
Phishing
• Automated social engineering via email.
• Targets:
o Usernames and passwords
o Credit card details
• Fake URLs redirect victims to attacker-controlled servers.

Frequency of Attack
Growth of the Internet
• From 231 ARPANET computers (1981) to millions today.
• Internet used for:
o Commerce
o Government
o Communication
Increased Attacker Collaboration
• Thousands of organized attacker groups.

Web Security By [Link] - 63-


• Distribution of:
o Vulnerability data
o Exploit code
o Attack tools (email, IRC, websites)
Automation and Scale
• Automated scanning and exploitation tools.
• High-speed connections enable attacks on millions of systems rapidly.
Honeynet Project Findings
(Often shown using time-to-compromise graphs)
• Average compromise time:
o 72 hours for Red Hat 6.2 (June 2001)
• Windows 98 with file sharing:
o Scanned hourly
o Compromised within a day
• Some systems compromised within 15 minutes.

Understanding Your Adversaries


Script kiddies
• Typically children or teenagers.
• Use pre-written scripts and tools.
• Dangerous due to:
o Lack of understanding of consequences
• Case studies:
o Gibson Research DDoS attack (13-year-old)
o “Mafiaboy” attacks (age 16)
Industrial spies
• Black market for stolen data.
• Activities:
o Extortion
o Selling trade secrets
• Illegal in many countries.
Ideologues and national agents
• Hacktivism:
o Political or ideological motivations
o Website defacement
• Possible state-sponsored attacks.
• Can affect third-party ISPs.
Organized crime
• Targets financial and sensitive data.
• Activities include:
o Fraud
o Money laundering
o Illegal trade coordination
• Global reach via the Internet.

Web Security By [Link] - 64-


Rogue employees and insurance fraud
• Insider threats:
o Trojan horses
o Logic bombs
• Motivations:
o Revenge
o Malice
o Insurance scams

What the Attacker Wants


(Typically illustrated using post-compromise usage diagrams)
Compromised systems are used for:
• Launching further attacks
• Distributed denial-of-service (DDOS)
• Running covert servers (e.g., IRC rendezvous points)
• Network surveillance
• Hosting contraband or stolen data
Reasons compromised systems are valuable
• High-speed connectivity
• Obfuscation of attacker identity
• Multi-jurisdiction attack paths

Tools of the Attacker’s Trade


nc (netcat)
• “Swiss Army knife” for TCP/IP.
• Functions:
o Data transmission
o Port scanning
o Server creation
trinoo (trin00)
• Distributed DoS attack server.
• Hidden presence.
• Unix-based versions available.
Back Orifice and Netbus
• Windows Trojan horses.
• Capabilities:
o Keystroke logging
o File access
o Remote command execution
bots
• Distributed attack agents.
• Used for:
o DDOS
o IRC control

Web Security By [Link] - 65-


• Can remain dormant.
root kits
• Provide superuser access.
• Hide attacker presence.
• Modify system utilities and logs.

Securing the Host Computer


Security Through Policy
• Security cannot rely solely on technical checklists.
• Network services inherently expose systems.
• Focus should be on policy-driven security practices.
Poor Security Practices (Nine Key Issues)
• Lack of security planning
• Cost-driven purchases
• Plaintext password transmission
• Improper use of security tools
• Unpatched software
• Poor threat monitoring
• Inadequate logging
• Weak backups
• Insufficient monitoring
Role of Policy
• Defines allowed and disallowed actions.
• Guides:
o Users
o Administrators
o Designers
Standards and Guidelines
Policy should define:
• Access authorization
• Security responsibilities
• Allowed content
• External access rules
• Testing requirements
• Incident response
• Policy updates
• External communication authority

Keeping Abreast of Bugs and Flaws


• Rapid global dissemination of vulnerability information.
• Administrators must:
o Monitor vendor bulletins
o Apply patches promptly
• Sources:

Web Security By [Link] - 66-


oVendor mailing lists
o FIRST teams (e.g., CERT/CC)
o Security mailing lists (bugtraq, nt-security)
Patch Management
• Verify authenticity (digital signatures, checksums).
• Avoid unofficial patches.
• Beware of malicious or poorly written fixes.

Choosing Your Vendor


• Security often overlooked in purchase decisions.
• Factors affecting security:
o Vendor code quality
o User base size
• High-usage platforms attract attackers.
• Risk of:
o Buggy software
o Beta/pre-beta deployments
Evaluation Criteria
• Vendor security reputation
• Patch responsiveness
• Design philosophy
• Feature minimalism
• Historical vulnerability trends
Procurement Requirements
• Proof of secure development practices
• Test documentation
• Vulnerability response policies
• Notification procedures
• Past security advisories

Installation I: Inventory Your System


• Document:
o Hardware serial numbers
o RAM, processors, options
• Store inventory securely in multiple locations.
• Software inventory:
o Vendor
o Version
o Activation codes (secured)
• Retain:
o Packaging
o Documentation
o Inserts (often contain critical warnings)

Web Security By [Link] - 67-


Installation II: Installing the Software and Patches
• Check vendor websites for:
o Patches
o Release notes
• Install patches in correct order.
• Disconnect system from Internet during installation.
• Installation sequence:
1. Base OS
2. OS patches
3. Applications
4. Application patches
• Maintain a detailed installation log.
Backup Strategy
• First full backup after installation.
• Second backup after customization.
• Store backups and media securely.
• Restrict physical access.
• Consider removing removable drives.

Minimizing Risk by Minimizing Services


• One of the most effective ways to secure a web server is to minimize the number of
services running on the host system.
• Each additional network service introduces its own security risks and attack
surfaces.
• By disabling nonessential services, administrators reduce the number of possible
entry points for attackers.
• Even services considered “safe” today may later be found vulnerable.
• Example (BIND vulnerability, 2001):
o Berkeley Internet Name Daemon (BIND) flaw allowed remote superuser
access.
o Systems running name servers on web servers were compromised.
o Systems that had disabled name services were not affected.
• Key principle: If you don’t need a service, disable it.

Making a Pre-Mac OS X Your Web Server


• Pre–Mac OS X systems (OS 7, 8, 9) offer inherent security advantages.
• These systems:
o Lack a command-line interpreter, making remote execution difficult.
o Do not enable many network services by default.
o Have historically stable and well-written code from Apple.
• Available Macintosh web servers:
o MacHTTP – free, simple administration.
o WebStar – commercial version by StarNine Technologies.
o WebStar Pro – SSL-enabled WebStar.

Web Security By [Link] - 68-


o Apple Personal Web Server – included with Mac OS 9 and some OS 8
versions.
• Mac OS X:
o Based on FreeBSD.
o Expected to have Unix-like security characteristics.

Operating Securely
• Security degrades over time due to:
o Installation of new software.
o Increased system complexity.
o Disabled security features for convenience.
o Newly discovered vulnerabilities.
• Security consultants often provide temporary improvements without long-term
maintenance.
• Conclusion: A secure system must be continuously maintained, not just initially
deployed.

Keep Abreast of New Vulnerabilities


• Vulnerabilities are now disclosed rapidly and publicly.
• Exploits often appear within hours of disclosure.
• Administrators must respond quickly to apply patches.
• Firewalls and IP filtering can limit exposure but:
o Firewalls themselves may have vulnerabilities.
o Some attacks exploit allowed protocols.
• Key takeaway: Continuous vigilance is essential.

Logging
• Logging records system and network activity.
• Unix and Windows systems allow flexible logging:
o Single or multiple files.
o Remote logging to other machines or devices.
• Importance of logs:
o Aid in incident recovery.
o Reveal attack methods.
o Provide forensic evidence.
• Logs should be:
o Enabled on all servers.
o Reviewed regularly.
• Commonly logged parameters:
o External and internal network utilization.
o CPU load.
o Disk usage.
• Logs also help in capacity planning.
• Web servers are a notable exception, often maintaining separate logs.

Web Security By [Link] - 69-


Setting up a log server
• Attackers often erase or modify logs after gaining access.
• Solution: Use a secured log server.
• A log server:
o Collects logs from other systems.
o Offers no services and no user accounts.
o Is the most secure system on the network.
• Can be placed:
o Inside the firewall.
o Outside the firewall.
o Or both (dual log servers).
• Log servers supplement, not replace, local logging.

Logging on Unix
• Unix logging uses:
o Facilities (source of message: kern, auth, news, etc.).
o Priorities (severity: info, alert, crit).
• Configuration file: /etc/[Link]
o Defines where log messages are sent.
• Log maintenance:
o Logs must be rotated and pruned.
o Tool: newsyslog
o Configuration file: /etc/[Link]

Logging on Windows 2000


• Controlled by the Windows logging service.
• Auditing is disabled by default on some versions.
• Auditing should be enabled to monitor:
o Login attempts.
o IP services.
• Excessive logging can generate large volumes of data.
• Logs are pruned automatically.
• Enabling auditing:
o Use Local Security Policy → Local Policies → Audit Policy.
o Refer to Figure 15-1 showing the Audit Policy interface.
• Viewing logs:
o Use Event Viewer.
o Retention time can be adjusted (see Figure 15-2).

Web Security By [Link] - 70-


Web Security By [Link] - 71-
Backups
• Backups are copies of data stored on long-term media.
• Security roles of backups:
o Recovery from hardware failures.
o Restoration after accidental deletion.
o Recovery from break-ins.
o Damage assessment via file comparison.
• Backup risks:
o Backup integrity must be verified.
o Backup servers may control client systems.
o Unencrypted backups can be intercepted.
o Backup media must be physically secured.
o ACL misuse in NT environments can expose all files.
• Best practices:
o Regular backups.
o On-site and off-site storage.
o Strong protection of backup media.

Using Security Tools


• Security tools help evaluate and improve security posture.
• Tools may be free or commercial.
• Five categories:
1. Snapshot tools
2. Change-detecting tools
3. Network scanners
4. Intrusion detection systems
5. Network recording and logging tools
• Attackers use similar tools; administrators should too.

Snapshot tools
• Perform static audits of system configuration.
• Example checks:
o File permissions (e.g., /etc/passwd).
• Tools:
o COPS – historical Unix tool.
o Tiger – modern Unix tool (Texas A&M).
o Windows tools: KSA, NAT, ScanNT, L0phtCrack.
• Should be run weekly or monthly.
• Output must be stored securely.

Change-detecting tools
• Detect unauthorized system changes after compromise.
• Help identify:
o Backdoors.

Web Security By [Link] - 72-


o Tampering.
• BSD/OS daily insecurity report:
o Compares /etc files using diff.
o Vulnerable if comparison files are compromised.
• Tripwire:
o Stores cryptographic checksums.
o Supports Unix and Windows.
o Can report to central console.
o Open-source version available.
• One of the most widely used intrusion detection tools historically.

Network scanning programs


• Scan systems for known network vulnerabilities.
• Tools:
o SATAN – historical, modular scanner.
o Commercial scanners (ISS, Axent, Network Associates).
o Windows analysis tools from SomarSoft.
• Regular scanning helps administrators identify weaknesses before attackers do.

Intrusion detection systems


• IDS act as burglar alarms for computer systems.
• Detect signs of intrusion during runtime.
• Types:
o Host-based IDS.
o Network-based IDS.
• Examples:
o Tripwire
o Dragon
o Cisco Secure IDS
o Realsecure
o Shadow
• Mostly commercial solutions.

Virus scanners
• Antivirus tools are essential for Microsoft platforms.
• Major vendors:
o Network Associates.
o Symantec.
• Unix/Linux:
o Very few viruses.
o Integrity tools like Tripwire are sufficient.
• Mac OS:
o Rare virus infections.
o Mostly macro-based threats.

Web Security By [Link] - 73-


• Majority of viruses target Windows environments.
• Frequent updates are required.

Network recording and logging tools


• Record all network traffic for later analysis.
• Useful for forensic investigations.
• Require large storage capacity.
• Examples:
o NFR
o NetVCR
o Silent Runner
o NetIntercept

Secure Remote Access and Content Updating


• Web content is usually created on desktops and uploaded.
• File transfer introduces authentication risks.
• FTP sends credentials in plaintext.

The Risk of Password Sniffing


• Password sniffing captures unencrypted credentials.
• Affects protocols such as:
o Telnet
o FTP
o POP3 / IMAP
o HTTP

Using Encryption to Protect Against Sniffing


Use a token-based authentication system
• Example: SecurID (see Figure 15-3).
• Generates one-time passwords.
Use a nonreusable password system
• Example: S/Key (see Figure 15-4).
• Pre-generated password lists.
Use a system that relies on encryption
• Examples:
o Kerberos
o SSH / SCP
o SSL / TLS
• Protects against sniffing and session hijacking.

Web Security By [Link] - 74-


Secure Content Updating
• Web servers should ideally be behind firewalls.
• VPNs provide the safest remote update method.
• Update methods include:
o scp/ssh
o FTP
o rcp/rdist
o NFS
o SMB
o Physical transfer

scp/ssh
• Secure, encrypted file transfer.
• Supports recursive directory copying.
• Uses public key authentication.
• Does not delete obsolete files by default.
• Synchronization tools may be required.

FTP
• Widely supported.
• Weak authentication.
• Vulnerable to sniffing.

Web Security By [Link] - 75-


• Can be enhanced using S/Key or SSH tunneling.

Unix rcp or rdist


• Can be secured using Kerberos or SSH.
• Supports IP-based authentication.
• Vulnerable to IP spoofing but less risky than plaintext passwords.

NFS
• Allows centralized content management.
• Filesystems should be mounted read-only.
• Performance impact possible.
• Suitable for multiple web servers.

Using SSH and FTP Together


• SSH tunnels FTP control traffic.
• Protects usernames and passwords.
• Data traffic remains unencrypted.
• Reduces overhead.

SMB
• Enables Windows file sharing.
• Requires careful firewall filtering.
• Disable guest accounts.
• Restrict administrative access.

Physical transfer
• No network exposure.
• Requires physical access.
• Suitable for high-security environments.

Dialup Modems
• Modems present hidden back doors.
• Many lack authentication.
• Organizations must:
o Establish modem policies.
o Conduct telephone scans.
• Scanning tools:
o PhoneSweep
o TeleSweep
o THL-SCAN
o Toneloc
• Telephone firewalls (e.g., TeleWall) provide strong protection.

Web Security By [Link] - 76-


Firewalls and the Web
• Firewalls contain attacks, not prevent them.
• Used for:
o Protocol control.
o Traffic filtering.
• Overreliance can weaken internal security.

Types of Firewalls
Packet filtering
• Router-based filtering.
• Fast and inexpensive.
• Does not inspect payloads.
Proxy
• Breaks direct connections.
• Uses intermediary servers.
• Proxy vulnerabilities possible.
Network Address Translation
• Hides internal IP addresses.
• Enables IP reuse.
• Simplifies ISP changes.
Virtual Private Networks
• Allow secure tunneling.
• Can be exploited if endpoints are compromised.

Protecting LANs with Firewalls


• Firewalls block dangerous traffic like ICMP Echo.
• Internal threats still remain.

Protecting Web Servers with Firewalls


• Limit traffic to required ports (80, 443).
• Isolate web server from internal network.
• Refer to Figure 15-5 illustrating firewall isolation.
• VPNs can be used for secure content updates.

Web Security By [Link] - 77-


3. Securing Web Applications
• Web servers are commonly used to display static content such as brochures, FAQs,
and catalogs.
• Dynamic web applications (e.g., shopping carts, personalized pages) require:
o Customized code
o Business logic execution
• This code executes each time a web page is fetched.
• Code usually runs as:
o Scripts
o Programs triggered by specific URLs
• Web servers combined with programming languages allow powerful applications.
• Problem: These programs may contain hidden flaws.
• Flaws are often not visible during normal operation.
• Attackers exploit these flaws to compromise:
o Web servers
o Underlying operating systems
• This chapter focuses on secure programming techniques for web applications.

A Legacy of Extensibility and Risk


• Web servers are highly extensible.
• Extensibility increases functionality, but also security risk.
• Four primary techniques are used to create web-based applications.

Web Security By [Link] - 78-


CGI
• Common Gateway Interface (CGI) was the first web extension mechanism.
• When a CGI URL is requested:
o Web server launches a separate process
o Captures program output
o Sends results to the browser
• Parameters are passed via:
o Environment variables
o Standard input
• CGI programs can:
o Perform database queries
o Run financial calculations
o Enable chat systems
• Early web innovations (search engines, tracking systems) used CGI.
• Risk: Any executable program can be run.

Plug-ins, loadable modules, and Application Programmer Interfaces (APIs)


• Second extension technique.
• Uses modules written in C or C++.
• Modules are loaded into the web server’s address space.
• Advantages:
o Faster than CGI
o No new process per request
• Disadvantages:
o Difficult to write safely
o A single bug can crash the entire web server
• Bugs affect both:
o Web server
o Host operating system

Embedded scripting languages


• Third technique for adding programmability.
• Scripts are embedded directly into web pages.
• An interpreter runs the script before sending output.
• Faster than CGI.
• Examples:
o Microsoft ASP
o PHP
o Server-side JavaScript
o mod_perl
• Widely used for dynamic web applications.

Embedded web server


• Web server functionality is embedded directly into the application.

Web Security By [Link] - 79-


• No separate web server process is required.
• Common in specialized systems and appliances.

• These extension techniques allow any program to run.


• Security consequences include:
o Running vulnerable programs
o Allowing outsider access
o Modifying or deleting critical files

Limiting Damage from Web Applications


• Two methods reduce potential damage:
1. Secure program design and inspection
2. Restricted execution environments
• On multiuser systems:
o Web servers run as restricted users (e.g., nobody, httpd)
o CGI and API programs inherit these privileges
• Some operating systems lack privilege separation:
o Windows 3.1
o Windows 95/98/ME
o Mac OS 7–9
• These systems cannot restrict CGI program access effectively.

Programs That Should Not Be CGIs


• Interpreters and shells should never be placed in cgi-bin.
• Examples:
o Perl interpreter ([Link]) on Windows
• Attackers can run arbitrary commands if such programs exist.
• Search engines can locate misconfigured servers automatically.
• Default scripts may remain installed even after upgrades.
• Example: phf script
o Distributed with NCSA and early Apache servers
o Allowed attackers to retrieve system files
• Demonstrates unintended side effects.

Unintended Side Effects


• CGI script in Example 16-1 is discussed.
• Script contains:
o A safe form-handling function
o A finger gateway program
• Normal usage:
o Displays an HTML form
o Accepts a user ID
• Figure 16-1:
o Shows the finger form displayed in a web browser.

Web Security By [Link] - 80-


• Figure 16-2:
o Shows expected output for a valid finger request.
• Hidden flaw:
o Allows attackers to execute arbitrary commands.
• Security flaws can remain dormant for years.
• Some flaws may be intentional back doors.

The problem with the script


• Vulnerable line:
• print `/usr/bin/finger $input{'command'}`;
• Uses Perl backquotes, which invoke the Unix shell.
• Shell interprets special characters.
• Normal execution:

Web Security By [Link] - 81-


• /usr/bin/finger spaf@[Link]
• Unix shell allows multiple commands per line.
• Attacker input:
• spaf@[Link] & /bin/ls -l
• Figure 16-3:
o Shows malicious input entered into the form.
• Figure 16-4:
o Shows directory listing output returned by the script.
• Potential attacker actions:
o View confidential files
o Delete data
o Launch denial-of-service attacks
o Gain remote shell access
• Key lesson: Never allow arbitrary command execution.

Web Security By [Link] - 82-


Fixing the problem
• Never trust user input.
• Filter input to allow only legal characters.
• Use whitelisting, not blacklisting.
• Example:
o Accept only alphanumeric characters, @, ., and –
• This blocks shell metacharacters such as:
o &, ;, '
• Using character selection is safer than filtering disallowed characters.
• Input rules depend on:
o Data type
o Shell and program behavior

Avoiding the Shell Entirely


• Use Perl’s system() function instead of backquotes.
• Prevents shell invocation.
• Improves security and performance.
• Directly executes the command with arguments.

Rules to Code By
• Most security flaws are programming bugs.
• Secure programs are also more reliable.

General Principles for Writing Secure Scripts


• Design before coding.
• Review design with another programmer.

Web Security By [Link] - 83-


• Write and test small sections.
• Check all values provided by the user.
• Validate arguments passed to system functions.
• Check all system call return codes.
• Use internal consistency checks.
• Include extensive logging.
• Avoid logging sensitive data.
• Keep critical code small.
• Review code from an attacker’s perspective.
• Use full pathnames.
• Set the working directory explicitly.
• Test with expected and unexpected input.
• Be aware of race conditions.
• Disable core dumps.
• Avoid world-writable directories.
• Do not trust source IP addresses.
• Implement load limiting.
• Use execution time limits.
• Set CPU usage limits.
• Avoid plaintext reusable passwords.
• Conduct peer code reviews.
• Reuse trusted, audited code.

The Seven Design Principles of Computer Security


• Least privilege
• Economy of mechanism
• Complete mediation
• Open design
• Separation of privilege
• Least common mechanism
• Psychological acceptability

Securely Using Fields, Hidden Fields, and Cookies


• Web applications split code between:
o Server
o Browser
• Attackers can:
o Modify form data
o Bypass JavaScript
o Send forged requests
• Browser-stored data must always be validated on the server.

Web Security By [Link] - 84-


Using Fields Securely
• Filter every field.
• Validate length.
• Verify selection list values.
• Always revalidate on the server.

Hidden Fields and Compound URLs


• Hidden fields store data in browser memory.
• Used for:
o Session tracking
o Shopping carts
• URLs can embed parameters directly.
• Problems:
o Back button issues
o Shared computers
o Log file exposure
o User manipulation
• Must defend against modified submissions.

Using Cookies
• Cookies store client-side state.
• Users can modify cookies.
• Problems include:
o Reuse after expiration
o Long-term storage
o User distrust

Using Cryptography to Strengthen Hidden Fields, Compound URLs, and Cookies


• Cryptography:
o Protects confidentiality
o Detects tampering
• Human-readable data replaced with encrypted blocks.
• Process includes:
o Marshalling
o Timestamping
o Compression
o Encryption
o HMAC
o Base64 encoding
• Prevents replay and modification attacks.

Example 16-2. Secure cookie generation and decoding


• Demonstrates secure_encode() and secure_decode().
• Uses:

Web Security By [Link] - 85-


o HMAC-MD5
o TripleDES
o Compression
o Base64 encoding
• Efficient even on slow hardware.
• Shows cryptography can be practical and fast.

Web Security By [Link] - 86-


Rules for Programming Languages
This section outlines rules for writing more secure programs in different programming
languages.
Rules for Perl
To secure Perl scripts, especially CGI programs:
1. Use Perl’s Tainting Features
o Enable tainting with -T at the beginning of scripts.
o Tainting marks all user-supplied variables as “tainted.”
o Tainted variables cannot be used in unsafe operations (e.g., file opening,
system calls).
o Untaint variables using Perl string match operations.
o Figure/Example: Example 16-2 shows secure cookie generation and
decoding, using functions secure_encode() and secure_decode().

Web Security By [Link] - 87-


2. Set PATH Environment Variable
o Must be a known safe value before calling system().
3. Filenames
o Perl ignores tainting for read-only files; always untaint filenames used in
writing operations.
4. SUID Scripts
o Use Perl’s emulation mode to handle SUID scripts safely on older Unix
systems.
5. PATH Security
o Always set the program’s PATH variable, even if not running SUID or Unix.
6. Interpreter and Libraries Security
o Ensure Perl interpreter and libraries are modifiable only by the administrator.

Security-Related CGI/API Variables


• HTTPS_RANDOM: 256-bit random value for each CGI invocation (Netscape).
• REMOTE_HOST: Hostname of client machine (e.g., [Link]).
• REMOTE_USER: Authenticated username (e.g., simsong).
• REMOTE_ADDR: Client IP address (e.g., [Link]).
• AUTH_TYPE: Type of authentication (e.g., Basic).

Rules for C
• Writing secure C programs is harder than Perl because C lacks automatic memory
management.
• Perl advantage: smaller, modular code; automatic memory handling.
• C advantage: speed, especially for CGI programs.

Security Guidelines for C


1. Check buffer boundaries when manipulating strings.
2. Use caution with unsafe library calls:
o sprintf(), scanf(), sscanf(), vsprintf(), realpath(), getopt(), getpass(), etc.
3. Watch for functions returning pointers to static storage; attackers can overflow
buffers.
4. Use ANSI C compiler with function prototypes. Consider analysis tools like Purify.
5. Enable compiler warnings:
o GNU C: -Wall
o MS VC++: /W4
o Replace unsafe functions:
Avoid Use instead
gets() fget()
strcpy() strncpy()
strcat() strncat()

Web Security By [Link] - 88-


6. File creation:
o New files: use O_EXCL | O_CREAT.
o Existing files: omit O_CREAT.
o Temporary files: tmpfile() or mkstemp() (avoid mktemp(); vulnerable to race
conditions).

Rules for the Unix Shell


• Avoid writing CGI scripts with sh, csh, ksh, bash, tcsh except for trivial scripts.
• Security issues are abundant; easy to make mistakes.

Using PHP Securely


Introduction to PHP
• Server-side scripting language, originally Personal Home Page → PHP3 → PHP
Hypertext Preprocessor.
• Runs on Unix/Windows with Apache/IIS.
• Advantages:
o Fast execution; interpreter built into web server.
o No special directory/executable required.
o Error display directly on web page.
o Database connection caching (MySQL).
o Powerful: open files, network connections, execute programs.

Example PHP Script:


<html><head><title>PHP Test</title></head>
<body>
<?php
echo "Hello World!<p>";
?>
</body></html>
• PHP code enclosed in <?php ... ?>.
• Variables: begin with $, untyped, auto-substituted in double-quoted strings.

Controlling PHP
• [Link] or Apache [Link] controls behavior.
• Example: enabling PHP3 safe mode in /htdocs but not /staffdocs.
<Directory /htdocs/>
php3_safe_mode on
</Directory>
<Directory /staffdocs/>
php3_safe_mode off
</Directory>

Understanding PHP Security Issues


• Shared hosting: users may access others’ files.

Web Security By [Link] - 89-


• Lax variable protections: default globals, hidden backdoors, downloaded scripts.
PHP Installation Issues
• Recommended as Apache module (faster).
• If installed as executable: place outside web hierarchy (/usr/local/bin/php).

PHP Variables
• Global variables include:
o CGI environment variables (HTTP_USER_AGENT, DOCUMENT_ROOT)
o GET, POST, Cookie, Server variables
o Variables in libraries
• Danger: variable shadowing; attackers can override expected values.
Example: Global Variable Attack
• $MAILDIR normally /var/spool/mail
• URL ?MAILDIR=/etc/passwd overrides variable.
• Solution: manually initialize variables:
$authorized = 0;
if(validate_user($user,$pass)) {
$authorized = 1;
}
• Best practice: set register_globals = off.

Database Authentication
• Avoid hardcoding usernames/passwords in scripts.
• Better: store passwords in secure file and read them.
$fp = fopen("/usr/local/adm/dbpasswords/http", "r");
$pass = fgets($fp,14);
fclose($fp);
mysql_pconnect("[Link]","http",$pass);

URL fopen()
• PHP can open URLs with fopen().
• Risk: attacker can manipulate include files via globals.
• Example: [Link] includes [Link]; attacker sets $langDir to external
URL.

Hiding PHP Scripts


• Keep scripts private; ensure always processed by PHP.
• Avoid exposing debugging variables (debug, showerrors).
• Web server configuration can hide PHP:
AddType application/x-httpd-php .bop .foo .133t
# or parse all HTML with PHP
AddType application/x-httpd-php .htm .html

Web Security By [Link] - 90-


PHP Safe Mode
• Disables dangerous functions based on script location.
• Useful for shared servers (ISPs).
• Restrictions include:
o File operations limited to UID of script owner.
o system() only executes scripts in safe_mode_exec_dir.
o dl(), backticks, shell_exec() disabled.

Scripts with Additional Privileges


• Avoid SUID/SGID unless necessary.
• Scripts running with higher privileges are common security risks.

PHP Configuration File Settings


Shaun Clowes’ Recommendations for Securing PHP Environments:
• set register_globals=off
o Prevents users from setting variables in PHP scripts.
• set safe_mode=on
o Enables PHP safe mode, improving security.
o Especially recommended for ISP environments.
o Quote: “This is a great option for ISP environments… but it can also be a
complete pain in the neck.”
• set open_basedir
o Restricts PHP to a specified directory hierarchy.
• set display_errors=off, log_errors=on
o Writes errors to a log file instead of the web browser.
o Makes debugging harder but prevents attackers from reverse-engineering
scripts.
o Recommendation: On development systems, display_errors=on; on
production, display_errors=off.
• set allow_url_fopen=off
o Prevents PHP from opening URLs when expecting files.

Writing Scripts with Additional Privileges


1. Use SUID root carefully:
o Needed only for tasks requiring superuser access (e.g., modifying
/etc/passwd).
o For restricted database access, create a special Unix user and SUID scripts to
that user.
2. Separate SUID functionality:
o If superuser access is rarely needed, isolate SUID operations in a separate
program with controlled interface.
3. Revoke privileges quickly:
o Use SUID/SGID early in the program and return effective/real UID/GID to
normal immediately after use.

Web Security By [Link] - 91-


4. Avoid shell scripts for SUID:
o Especially csh and derivatives.
5. Use separate users/groups per application:
o Prevents abuse amplification.
6. Use setuid() and setgid() functions to bracket privileged code:
7. setuid(0); // Become superuser to open master file
8. fd = open("/etc/masterfile", O_RDONLY);
9. setuid(-1); // Revoke superuser
10. if(fd<0) error_open(); // Handle errors
11. Use full pathnames for all file operations.
12. Use chroot() for further restriction:
o Changes root directory to limit process access.
o Example: Restrict program to /usr/local/logs:
o chroot("/usr/local/logs");
o Recommended only for CGI programs, not API modules.
o Easier to implement in Perl than C.

Connecting to Databases
• CGI scripts often connect to external databases for:
o User preferences
o Shopping carts
o Order processing
• Security concerns:
o Each script execution may open a new connection, or use persistent
connections.
o Database-backed websites are powerful but can reduce overall security if
attackers execute arbitrary SQL.
o Example: Theft of credit card numbers due to insecure database access.

Protect Account Information


• Databases require username/password authentication.
• Common but unsafe practice: Hard-coding credentials in scripts.
Problems:
o Scripts can be viewed by attackers → credentials exposed
o Multiple scripts may require the same credentials → redundancy
o Changing credentials requires editing multiple scripts → risk of mistakes
• Better approach: Store credentials in a separate file, read them at runtime.
• $fp = fopen("/usr/local/adm/dbpasswords/http", "r");
• $pass = fgets($fp,14);
• fclose($fp);
• mysql_pconnect("[Link]","http",$pass);

Use Filtering and Quoting to Screen Out Raw SQL


• Always filter user input to ensure only allowable characters.

Web Security By [Link] - 92-


• Properly quote user data before sending to SQL server.
• Unsafe example:
• $name = param('name');
• sql_send("insert into names (name) value ('$name');");
o Input "Simson Garfinkel')"; delete from names; results in:
o insert into names (name) value ('Simson Garfinkel')"; delete from names; ');
o Executes insertion, deletion, and generates a SQL error.
• Safe approach:
o Use a quote function:
o sub squote {
o my $ret = $_[0];
o $ret =~ s/\'/\\'/g;
o return '\'' . $ret . '\'';
o }
o $qname = squote(param('name'));
o sql_send("insert into names (name) value ($qname);");
o Or use variable binding with precompiled SQL queries:
o $func = sql_compile("insert into name (name) value (@)");
o $name = param('name');
o sql_bind($func,1,$name);
o sql_exec($func);

Protect the Database Itself


• Network security:
o Use firewalls to prevent outside access.
o Recommended: Separate Ethernet adapters and firewall appliance between
web server and database (Figure 16-5).
• Limit logins:
o Only system administrators and DB admins should have login access.
• Physical and maintenance security:
o Ensure database server is backed up, physically secure, and maintained like
other critical servers.

Web Security By [Link] - 93-

You might also like