WEB APPLICATION SECURITY TESTING – 8. ATTACKING ACCESS CONTROLS

This notes is for learning/educational purpose only. Use it at your own risks. 

Authentication and Session management ensure that you know who is using the application. Similarly, Access Controls is defense mechanism which limits what actions are possible for authenticated users. It must be tested for every request and operation.

COMMON VULNERABILITIES

Access controls can be divided into three broad categories – Vertical, Horizontal and Context-Dependent.

  • Vertical Privilege Escalation – allow user to access a different part of app’s functionality. Like, escalating from user to administrator.
  • Horizontal Privilege Escalation – allow user to access a wider range of resources of same type. Such as reading another user’s email.
  • Context-Dependent (Business Logic Exploitation) – User can do things that should not be possible in context. Like, performing tasks out of order. Or, bypassing payment step when checking out.

Completely Unprotected Functionality

  • Functionality can be accessed by anyone who knows the URL
  • OWASP refers this as “Unsecured Direct Object Access”, also known as “Security through Obscurity”
  • Inspecting client side code may reveal privileged URLs

Identifier-Based Functions

  • Identifier for a document passed to server in parameter
  • Access controls may be broken so everyone with URL can view the document. This often happens when developers find it too difficult to share session-based security model between servers using different technologies.
  • Document identifiers might be predictable.
  • URLs are not treated as secrets – often visible in logs or elsewhere in app

Multistage Functions

  • App may enforce access control in early step but not test it again in later step.
  • Attacker can skip steps and escalate privileges

Static Files

  • Anyone with direct link to file can view and/or download the file if app-level code is executed for access.

Platform Misconfiguration

  • Access to specified URL paths are restricted.
  • Platform level configuration allow or deny access based on following – HTTP request method, URL path, User role

Verb Tampering:

  • Access control rule may apply only to POST method. Using GET/HEAD may perform admin-level tasks.
  • Unrecognized HTTP methods may default to GET

Insecure Access Control Methods

  • Parameter based access control:
    • Privilege level in hidden form field, cookie or query string parameter.
    • Attacker can just add parameter to gain privileges
  • Referer based access control:
    • HTTP referer header grants access
    • User can modify that field to gain privilege
  • Location based access control:
    • Often uses geolocation of user’s IP address
    • Using web proxy based in required location might bypass this
    • Using VPN that terminates in required location might bypass this
    • Using mobile device that supports data roaming might bypass this
    • Direct manipulation of client-side mechanisms for geolocation can bypass this

ATTACKING ACCESS CONTROLS

Testing With Different User Accounts

  • Map contents of app using two user accounts and compare them

Testing Direct Access to Methods

  • Might be able to guess other methods from the ones you see
  • Test them to see if access is properly limited

Testing Controls Over Static Resources

  • Walk through app while logged in as admin
  • Note URLs of high privilege resources
  • Login as low privilege user
  • Try to access those URLs found earlier
  • Try to guess other sensitive URLs from the patterns of URLs you have found

Testing Restrictions on HTTP Methods

  • Login as admin and find sensitive requests
  • Try other methods, POST, GET, HEAD, invalid
  • Test with low privileged account

SECURING ACCESS CONTROLS

  • Do not rely on user’s ignorance of URLs or identifiers
  • Do not trust any user-supplied parameters like admin=True
  • Do not assume users will access pages in intended sequence
  • Do not trust user not to tamper with data; revalidate it before using it

Best Practices

  • Explicitly evaluate and document access control requirements for every unit of app functionality
  • Drive all access control decisions from user’s session
  • Use a central app component to check access controls; use it for every client request and mandate that every page must include an interface to this component
  • For sensitive functionality, restrict access by IP address
  • Protect static content by – passing filename to server side page that implements access control logic, or use HTTP authentication or other feature to restrict access
  • Do not trust resource id from client, validate them on server
  • Consider requiring re-authentication or two factor authentication for security-critical app functions
  • Log events using sensitive data or actions

Advantages of Central Access Control

  • It increases clarity of access control within application.
  • It makes maintainability more efficient and reliable, required changes are needed to be done once.
  • It improves adaptability. New access controls can be added and used easily.
  • It results in fewer mistakes and omissions.
Advertisements

WEB APPLICATION SECURITY TESTING – 7. ATTACKING SESSION MANAGEMENT

This notes is for learning/educational purpose only. Use it at your own risks. 

THE NEED FOR STATE

Session management enables application to identify a given user over number of different requests. It is fundamental security component and also a prime target for attackers.

With session management attacks, a user can masquerade as another user or escalate privileges to admin. Attack could be as simple as incrementing the value of a token.

Vulnerabilities are of two categories:

  • Weakness in generation of session tokens
  • Weakness in handling session tokens throughout their life cycle

Finding Real Session Token:

To find token, establish session and then replay request. Systematically remove each item you suspect of being real token.

Alternatives to Sessions:

  • HTTP Authentication – Pass credentials with every request in HTTP headers.
  • Sessionless State Mechanisms – App doesn’t issue session tokens or manage the state. Transmit all data required to manage the state via client in cookie or hidden form field. Example- ASP.NET ViewState

Securing ViewState:

  • Data must be protected, usually as binary blob that is encrypted or signed, to prevent re-use on another machine.
  • ViewState uses Base64 and hash made from Machine Authentication Code. Include’s machine’s MAC address.
  • Expiration time enforces session timeouts

Identifying Sessionless State Mechanisms:

  • Token-like data item with more than 100 bytes long. Possibly in response to every request.
  • Data is encrypted (structureless) or signed (structured + random bytes)
  • App rejects attempts to submit same item with more than one request

WEAKNESSES IN TOKEN GENERATION

Meaningful Tokens

  • Components in structured tokens are generally – username, userid, first name, last name, email address, user role, timestamp, client ip address, predictable number etc.
  • Common encoding schemes used are – XOR, Base64, Hexadecimal ASCII codes.

HACKSTEPS:

  1. Obtain token, modify it in systematic ways. Change it one byte or one bit at a time and resubmit to see if its still accepted. (Burp Intruder’s “char frobber” function)
  2. Login as several users at different times. Similar usernames or email addresses. Record tokens. Analyze tokens for correlations and look for encoding or obfuscation.
  3. Repeating letters produce repeating encoded characters if XOR is used.
  4. Use patterns found to try guessing tokens of other users.

Predictable Tokens

  • From a sample of tokens, it may be possible to predict valid tokens.
  • Commercial implementations such as web servers or app platforms may be more vulnerable. Because its easier to gather large sample of tokens from own test system.

Three common sources of predictable session tokens:

  • Concealed sequences: Base64 encoded. Decode it and use hex form. Calculate difference between tokens. It will reveal the concealed pattern.
  • Time dependency: Number increments based on time elapsed, probably in milliseconds.
  • Weak random number generation: Jetty is java based web server. It calculates pseudorandom session tokens with ‘linear congruential generator’. Multiplies previous number by constant, adds another constant and truncates to 48 bits. Given on values, others can be predicted.

 

  • PHP 5.3.2 and earlier uses session token generated from clients ip, epoch time at token creation, microseconds at token creation, and linear congruential generator.
  • Use burp sequencer to test randomness of tokens.

Encrypted Tokens

Attacker can sometime tamper token’s values without decrypting.

ECB Ciphers:

  • Electronic Code Book
  • Input broken up into blocks, often 8 bytes long
  • Symmetric encryption, no randomness
  • Each input block encodes to single output block.
  • Patterns of input is preserved in output

CBC Ciphers:

  • Cipher Block Chain mode
  • XOR’s each block of plaintext with preceding block of cipher text
  • Modify single byte of ciphertext, and that block will decrypt to junk but next block will be meaningful only slightly altered.
  • Test for CBC cipher manipulation vulnerability by bit flipping method. 8 requests per byte.

WEAKNESSES IN SESSION TOKEN HANDLING

SSL protects tokens in transmission, but some attacks like XSS to obtain token will still work.

Disclosure of Tokens on Network

  • Tokens transmitted without encryption can be eavesdropped.
  • Cookies containing session token when sent over HTTP can be captured. Using Firesheep firefox plugin.
  • Stealing user password may not work (may require OTP) but stealing session token and hijacking session may work (No notification of extra login).
  • App may use HTTPS during login but use HTTP to see authorized content.
  • If App uses same token as on preauth pages and on all subsequent pages after login, attacker can steal it.
  • If App uses new token & HTTPS on login and all subsequent pages, but user navigates to an HTTP page with back button exposing the token.
  • SSLstrip – Attacker alters page link to use HTTP and forwards requests to server via HTTPS.

Disclosure of Tokens in Logs

  • Transmitting token as URL query string might appear in system logs, user’s browser logs, web server logs, Logs og ISP proxy servers and Logs of reverse proxies.
  • If a mail app transmits session token in URL, then attacker can send his web server link to user via email, on clicking attacker will get session token in ‘Referer’ header.

Vulnerable Mapping of Tokens to Sessions

  • Weakness in mapping the creation and processing of session tokens to individual users.
  • Simple weakness is to allow multiple valid tokens concurrently assigned to same user account.
  • Another weakness would be using static tokens (same token sent to a user on every login)
  • Another flaw would be when session is base64 encoded of username and some random number, attacker can change username

Vulnerable Session Termination

  • Session may remain valid for days after last request is received
  • Ineffective logout functionality
  • Logout merely deletes cookie but does not invalidate it or logout runs on client side, server is unknown

Client Exposure to Token Hijacking

  • Attacker steals cookie, may be via XSS
  • Session Fixation – attacker feeds token to user, user logs in, attacker hijack the session.
  • Session fixation is possible if app doesn’t issue fresh token after second login or uses same token issued to unauthenticated user for login. If session token format is identified or token can be modified and app accepts it, its session fixation.
  • CSRF – Tricks user into submitting a request containing cookie that goes to attacker’s server

Liberal Cookie Scope

  • When cookie is set, server can set domain and path, cookie is used for. By default, all subdomains are included for which cookie is valid.
  • Path based restriction is more stricter than what is imposed by same-origin policy.

SECURING SESSION MANAGEMENT

Generate Strong Tokens

  • Use extremely large set of possible values
  • Contain strong source of pseudorandomness, ensuring an even and unpredictable spread of tokens across range of possible values.
  • Tokens should contain no meaning or structure.
  • All data about session owner and status should be on server in session object

Source of Entropy (Randomness):

  • Source IP address and port number from which request was received
  • User-Agent header in request
  • Time of request in milliseconds
  • Add secret known only to server and then hash it with SHA256 or stronger. Change secret on each reboot

Protect Tokens Throughout their Life Cycle

  • Transmit tokens only over HTTPS (secure and httponly)
  • Use HTTPS for every page in app
  • Don’t put session tokens in URL
  • Logout should invalidate session token on server
  • Session should expire after brief period of inactivity
  • Do not allow concurrent logins
  • Protect diagnostic or admin functions that save tokens or don’t save tokens in them
  • Restrict domain and path for session cookies
  • Audit codebase and remove XSS esp. second order or stored XSS
  • Don’t accept tokens submitted by unrecognized users
  • Use two factor authentication, makes CSRF and other methods difficult
  • Use hidden fields rather than session cookies
  • A new page token is created every time user requests an app page, if verification fails, terminate session. Also prevents pages being used out-of-order

Log, Monitor and Alert

  • Request with invalid tokens should raise IDS alerts.
  • Alert users of incidents relating to their sessions.

Reactive Session Termination

  • Terminate session if request has modified form field or URL query string parameter
  • Terminate session if strings associated with SQLi or XSS
    Terminate session if input violates validation checks

WEB APPLICATION SECURITY TESTING – 6. ATTACKING AUTHENTICATION

 

This notes is for learning/educational purpose only. Use it at your own risks. 

 AUTHENTICATION TECHNOLOGIES

Wide range of technologies are available for authentication mechanism :

  • HTML form-based authentication
  • Multifactor mechanism like combining password and physical tokens
  • Client SSL certificates and/or smartcards
  • HTTP authentication
  • Windows-integrated authentication using NTLM or Kerberos

90% of web apps use form based authentication.

  • More secure methods would be two-factor authentication i.e. PIN from token, SMS message or mobile app, in addition to password.
  • Cryptographic methods are client side SSL certificate, smartcards etc, but expensive.
  • HTTP authentication including windows integrated are often found on intranets, not on internet.
  • Third party authentication services i.e. using OAuth etc.

DESIGN FLAWS IN AUTHENTICATION MECHANISMS

Bad Passwords

  • Short or blank, dictionary based, same as username or set to default value.

Brute-forcible Login

  • Attackers use list of common passwords. Account lockout is the defense.

Verbose Failure Messages

  • Friendly for legitimate users but helpful for attackers i.e. harvesting valid username

Vulnerable Transmission of Credentials

  • Unencrypted credentials should never be sent even over HTTPS

Password Change Functionality

  • Periodic password change mitigates password compromise is dubious claim. Change password if its compromised.
  • Password change system is vulnerable if:
    • It reveals a username is valid
    • Allows unrestricted guesses of existing password field
    • Checks if new password and confirm new password have same value after validating existing password.

Forgotten Password Functionality

  • Often the weakest link, uses secondary challenge.
  • Small set of possible answers, can be brute-forced or found from public information.
  • Some apps let user in after challenge without login.
  • Some apps disclose password to user.
  • Some apps ask user email id for sending password reset link.

“Remember Me” Functionality

  • Sometimes a simple persistent cookie.
  • No need to login if username or session id can be guessed or found
  • If encrypted, it can be stolen via XSS or by getting acces to user device.

User Impersonation Functionality

  • Company personnel may have access to impersonate users, implemented either as hidden function, guessable session number or fixed backdoor password.

Incomplete validation of credentials

  • Some apps truncate passwords without telling users and also strip unusual characters.

Non-unique usernames

  • Rare, but it might be possible to create new account with same username.

Predictable usernames

  • Automatically generated usernames.

Predictable Initial passwords

  • Usually for user accounts created in large batches. All having same initial password.

Insecure distribution of credentials

  • Passwords sent by email, sms etc.
  • Activation URLs may be predictable.
  • Some apps email new password after each password change.

IMPLEMENTATION FLAWS IN AUTHENTICATION

Fail-Open Login Mechanisms

Blank, invalid username may cause exception in login routine, very long or short values or different character sets and allows the user in.

Defects in Multistage Login Mechanisms

  • May allow user to skip steps.
  • May trust data that passes step one, but let user change it, so invalid or locked out accounts remain available.
  • May assume that same username applied to all three stages but not verify this.
  • May use randomly chosen question to verify user, but let the attacker alter question in hidden HTML or cookie.

Insecure Storage of Credentials

  • Plain text passwords in database.
  • Hashes with MD5 or SHA1, easily cracked.

SECURING AUTHENTICATION

Use Strong Credentials

  • Minimum password length, use of alphanumeric and typographic characters.
    Avoid dictionary words, similar to username or old passwords

Unique usernames

  • Auto generated usernames or passwords should be long and random, so they cant be predicted.
  • Allow users to set strong password.

Handle Credentials Secretively

  • Protect them when created, stored and transmitted.
  • Whole login page should be HTTPS, not just login button.
  • Use POST and don’t put credentials in URL or cookies
  • Don’t transmit credentials back to client
  • Securely hash credentials on server
  • Hashing- Password hashes must be salted (adding random bytes to password before hash) and stretched (many rounds of hashing i.e. 5000 rounds for SHA512)
  • “Remember Me” functionality should remember only non-secret items i.e. usernames
  • If password is stored locally, it should be reversibly encrypted with key known to server only
  • Capture some login info with drop down list instead of text fields to defeat key-loggers

Validate Credentials Properly

  • Validate entire credentials with case-sensitivity
  • Terminate session on any exception
  • Review auththentication logic and code
  • Strictly control user impersonation
  • Multistage login-
    • All data and results of progress must be held in server-side session object not on client
    • No item of information should be submitted more than once by user
    • No means to modify data after submission
    • First task of every stage should be to verify that all prior stages have been correctly completed
    • Always proceed through all stages, don’t give attacker any info about which stage failed

Prevent Information Leakage

  • All authentication failures should use same code to produce same error message.
  • Account lockout can be used for username enumeration

Prevent Brute-Force Attacks

  • Using unpredictable usernames makes brute force attacks more difficult
  • Using different usernames with same password for an attack, can be mitigated with strong password rules i.e. CAPTCHA

Prevent Misuse of Password Change Function

  • Prevent changing username.
  • Require user to enter old password
  • Require new password twice
  • Show same error message for all failures
  • Out-of-band password change notification

Prevent Misuse of Account Recovery Function

  • For security critical apps, require out-of-band account recovery
  • Don’t use password hints
  • Email unique, time-limited, unguessable, single-use recovery URL
  • Don’t let users write their own challenge questions and don’t use questions with low-entropy answers

Log, Monitor and Notify

  • Log all authentication related events and protect logs from unauthorized access
  • Anomalies like brute force should trigger IDS alerts
    Notify users of any critical security events
    Notify users in-band of frequent security events i.e. time and source of last login

WEB APPLICATION SECURITY TESTING – 5. BYPASSING CLIENT-SIDE CONTROLS

This notes is for learning/educational purpose only. Use it at your own risks. 

 TRANSMITTING DATA VIA THE CLIENT

It is common for a server to send data to client and for client to repeat that same data back to server. Developers often assume that client wont modify the data. One might wonder why, server needs to transmit to client and get it back. Various reasons could be:

  • Removes the need of tracking all kind of data in user’s session, reducing amount of per session data stored on server, cam improve app’s performance.
  • If app is on multiple servers, user might interact with any of them, So sharing data between servers might not be straightforward than sending it to client.
  • Integration with third party component can also make it difficult.
  • Sometimes tracking a new piece of data might require updating core server-side API.

Hidden Form Fields – Capture with intercepting proxy, modify and replay.

HTTP Cookies – Capture with intercepting proxy, modify and replay.

URL Parameters – Capture with intercepting proxy, modify and replay.

The Referer Header –  Capture with intercepting proxy, modify and replay.
Opaque Data – Obfuscated or encrypted data i.e. session tokens, anti-csrf tokens, one-time access URLs.

  • If plaintext is known, decipher obfuscation algorithm.
  • By extrapolating app’s functionality, obtain required string.
  • If impenetrable, replay value in other context to achieve malicious effect.
    Else, attack server side logic that deobfuscate the opaque data by sending malformed variation i.e. containing overlong values, different character sets etc.

The ASP.NET ViewState – It contains serialized information about state of current page. Employed for server performance, it can also store arbitrary info across successive requests. It is base64 encoded string. Decoding from wrong position will show gibberish. Start from four adjacent offsets into encoded string. ViewState might be protected with MAC protection (indicated by presence of 20 byte hash at end of structure). MAC protection may be enabled or disabled on per page basis. Use burp to decode ViewState.

CAPTURING USER DATA: HTML Forms

Client side validation can improve performance and user experience but validation should not be trusted and must be repeated on server.

Length Limits 

  • If ‘304 Not Modified’ is received, then remove the If-Modified-Since and If-None-Match headers.

Script-Based Validation

  • Replace value after script runs, or disable JavaScript or modify the script.
    To test all cases, put invalid data in one field at a time.

Disabled Elements

  • Value of disabled parameter is not sent to server, so you can add the same parameter and server might fall for it.

NOTE: In Burp, goto Proxy > Options in ‘Response Modification’ provide options to remove webpage defenses.

CAPTURING USER DATA: Browser Extensions

Browser extensions can capture data in various ways – input forms, OS file system, registry etc. Developers might assume that they cannot be circumvented. So they can be fruitful target for discovering vulnerabilities in webapps.

Common Browser Extension Technologies

  • Java applets, flash, silverlight are common extensions. They are compiled to an intermediate bytecode and they execute within VM that provides sandbox environment for execution. They may use remoting frameworks to transmit complex data structures or serialized objects over HTTP.
  • Java applets run in JVM, sandboxed by Java Security Policy.
  • Flash runs in flash virtual machine, sandboxed from host computer. AS3 adds remoting capability with Action Message Format serialization.

Approaches to attack Browser Extensions

  • Intercept requests and responses in proxy, which can be encrypted, obfuscated or serialized. One may not explore all business logic of component from intercept unless component is closely analyzed.
  • De-compile bytecode and read source code or run it in debugger. Time consuming and requires detailed understanding of technologies.

Intercepting Traffic from Browser Extensions

  • It allows to defeat server-side controls.
  • Serialized data is tricky to modify. Unpack it, edit it and repack it correctly to avoid parsing errors. Serialization format can be inferred by type of client component but evident by close inspection of HTTP messages.
  • HTTP messages containing java serialized objects can be identified with Content-Type header having value of ‘application/x-java-serialized-object’. It can be modified with DSer plugin of burp suite.
  • Flash serialization can be identified with Content-Type header with ‘application/x-amf’ value. Burp natively supports AMF format.
  • Silverlight uses WCF employing .NET binary format for SOAP (NBFS) identified with Content-Type header with ‘application/soap+msbin1’ value. WCF binary SOAP plugin by Brian Holyfield can be helpful.

Obstacle to intercepting traffic from browser extension-

  • Components might be handling HTTP proxies or SSL or both.
  • Components may issue own HTTP requests outside browser APIs. So it cant be intercepted. Modify the hosts file and use invisible proxying.
  • If component is rejecting proxy cert, then configure proxy to use master CA certificate (used to sign valid per-host certificates for each site one visit) and install CA cert in computer’s trusted certificate store.
  • If component is using protocol other than HTTP, network sniffer or function hooking tool might be required like Echo Mirage.

TIPS: Ensure proxy is correctly intercepting all traffic, check with sniffer. Use appropriate serialization unpacker. Review responses from server that trigger client-side logic, you may be able to unlock a client GUI to reveal privilege actions. Look for correlation between critical actions and communications with server.

De-compiling Browser Extensions

Most thorough method is to decompile object and perform review of source code. Change the code if necessary and recompile it. Apps may use defensive measures to obfuscate bytecode.

Extension objects and decompiler:

  • Java applets are usually .jar files containing .class files with bytecode. Silverlight objects are .xap files containing .dll files with bytecode. Both are zip archive, rename extension & unzip it. Flash objects are .swf files, no unpacking required.
  • Use Jad decompiler for java. Flasm or Flare for flash. SWFScan was bundled into WebInspect. Silverlight use .NET reflector.

Working with Source code:

Review source code, understand how component works and what functionality it contains. Look for:

  • Input validation or security relevant logic and events.
  • Obfuscation or encryption routines used to wrap user input before sent to server.
  • Hidden client side functionality or references to server side functionality.

Recompile and Execute:

  • Use javac for java program to recompile.
  • Use flasm for flash file to reassemble modified bytecode.
  • Use Visual Studio to recompile for silverlight.

One can undo a lot of obfuscation by running obfuscated bytecode through obfuscator second time. Useful obfuscator for java is Jode.

Attaching a Debugger

Decompilation is most complete method of understanding and compromising browser extension. Because debugger is working at bytecode level, it can be used to control and understand flow of execution.

  • JavaSnoop is java debugger that can integrate Jad to decompile source code, trace variables, set breakpoints on methods and modify parameters. Run JavaSnoop before target applet is loaded.
  • JSwat is alternative tool for debugging java. Decompile, modify and recompile key class file and use JSwat to hotwap into running app. Launch applet using appletviewer and then connect JSwat to it.

Native Client Components

  • Some actions cannot be conducted from inside sandbox i.e. if user has anti-virus or proxy settings etc.
  • Such actions require use of native code components which integrate local app functionality with web app. Native client components are often delivered via ActiveX controls. It can be little hard to decipher as there is no intermediate byte code.
  • OllyDbg is windows debugger that can be used to step through native executable code, set breakpoints and apply patches to executables.
  • IDA Pro is disassembler that can produce assembly code from native executable code.

HANDLING CLIENT SIDE DATA SECURELY

Transmitting Data Via the Client

  • Don’t send critical data like prices from client. Send product id and lookup price on server.
  • If you must send, then sign and/or encrypt it to avoid user tampering. But it may be vulnerable to replay or other crypto attacks.

Validating Client-Generated Data

All client side validation methods are vulnerable. They can be useful for performance but they can never be trusted. So always validate on server.

Logging and Alerting

  • Server side intrusion detection defenses should be aware of client side validation.It should detect invalid data as probably malicious, triggering alerts and log entries.
  • May terminate user session or suspend user account.

 

WEB APPLICATION SECURITY TESTING – 4. APPLICATION MAPPING

This notes is for learning/educational purpose only. Use it at your own risks. 

First step to attack an application is to gather and examine some key information.

  • Enumerate application’s content and functionality.
  • Some functionality might be hidden requiring guesswork and luck to discover.
  • Examine every aspect of behavior, security mechanisms and technologies.
  • Helps in determining attack surface and vulnerabilities.

ENUMERATING CONTENT & FUNCTIONALITY

Majority of content and functionality can be identified via manual browsing. To perform rigorous inspection of enumerated content and to obtain comprehensive record of everything identified, more advanced techniques must be employed.

Web Spidering

  • Requesting web pages recursively by parsing.
  • Webapp Spiders can parse HTML forms, fill forms with preset or random values to submit.
  • Webapp Spiders can also parse client side JS to extract URLs.
  • Common web app spidering tools are – Burp Suite, WebScarab, ZAP and CAT.

Robots.txt

  • Intended to stop search engines from indexing urls.
  • May guide spiders to interesting content.

Limitations of Automatic Spidering

  • May fail to handle unusual navigation mechanisms i.e. Menus created dynamically.
  • Links buried in compiled client-side objects i.e. flash or java might be missed.
  • Forms may have validation checks.
  • Spiders fetch each URL once, but app using forms-based navigation may return different content and functions for same URL.
  • Some apps place volatile data within URLs i.e. timers or random number seeds. Spider will fetch same page over and over thinking its new and finally might freeze up.
  • Spiders must be able to submit valid credentials, perhaps using valid cookie. However, spiders often break authenticated session by requesting logout function or submitting invalid input to sensitive function or requesting pages out-of-sequence.
  • Spiders may find administrative page and click every link i.e. delete user, shut down db or server etc.

User directed Spidering

It is more sophisticated and controlled technique than automated spidering. User walks through app using browser connected to Burp. Proxy collects all requests and responses.

So user can follow complex navigation mechanisms. User can enter valid data where needed and avoid dangerous functionality.

TIP: Other tools useful during mapping are browser extensions performing HTTP and HTML analysis. i.e. IEWatch in IE. It analyzes every app page to display links, scripts, forms and think-client components.

HACKSTEPS For Spidering:

  1. Configure browser to use local proxy i.e. Burp or WebScarab
  2. Browse entire app normally, visit every link/url, submit every form, proceed with multistep functions. Try browsing with JS enabled and disabled, cookies enabled and disabled.
  3. Review sitemap generated. Identify if any app content/function you did not visit.
  4. Tell tool to actively spider site using already enumerated content. Identify URLs that are dangerous or likely to break app session & configure spider to exclude these from scope.

Discovering Hidden Content

  • Finding it requires automated testing, manual testing and luck.
  • It can be testing or debugging feature left in application. Or it can be feature for different category of users. There can be source files, backup copy of files, backup archive of entire source code, configuration files, log files or new functionality yet to be linked etc.

Brute Force Techniques
When the user-directed spidering has left with some URLs. Brute forcing the URLs for hidden directories or sub-directories using list of common directory names can be useful. This can be done with Brup Intruder.

NOTE: Some apps might respond to non-existent resource with 200 OK and error message and non-200 response for existent resource.

  • 302 Found – If redirect is to login page, resource might be accessible to authenticated users only. If redirect is to an error, this indicates a different reason. If redirect is to another location, redirect may be part of apps intended logic, & this should be investigated further.
  • 400 Bad Request – App may use custom naming scheme for directories and files within URLs. It is also possible that word list contains some whitespace or other invalid syntax.
  • 401 Unauthorized or 403 Forbidden – Requested resource exist but may not be accessed by any user.
  • 500 Internal Server Error – App expects certain parameters to be submitted when requesting resource.

HACKSTEPS for Discovering Hidden Content:

  1. Make manual requests for valid and invalid resources and identify how server handles
  2. Use sitemap as basis for automated discovery of hidden content
  3. Make automated requests for common filenames and directories to highlight results for invalid resources.
  4. Capture responses received from server and manually review them to identify valid resources.
  5. Perform exercise recursively as new content is discovered.

Inference from Published Content

  • Identify patterns if any from discovered URLs or content to customize enumeration exercise.
  • Names may use numbers or dates.
  • Comments may include DB names or SQL query strings.
  • Applets and ActiveX controls may have sensitive information.
  • Search for temp files created by tools and file editors. i.e. .tmp
  • .DS_Store – a directory index created by Mac OS X
  • Advanced search with site:, link:, related: google operators.

Dirbuster project

Useful when performing automated content discovery tasks. It includes large lists of directory names ordered by frequency of occurrence.

Google’s SkipFish

Vulnerability scanner but main strength is finding files and folders.

Nikto and Wikto

  • Scan servers for known vulnerable files and versions. Wikto is windows version and Nikto is Linux version.
  • Has false positives like other, verify results with manual testing.
# nikto -host blog.saurabh.world

Functional Paths

  • Different from old style tree-structured file system.
  • Every request goes to same URL, but parameters specify function.

HACKSTEPS for Enumerating Functional Paths:

  1. Identify any instance where functionality is accessed by passing name of function in parameter
  2. Identify system behavior with valid and invalid parameter values. Find attributes of responses that indicate ‘hits’. Breakdown enumeration in multiple steps if multiple parameters are used to access a function.
  3. Compile a map of app content based on functional paths, showing all enumerated functions and logical paths and dependencies between them.

Discovering Hidden Parameters

  1. Use list of common debug parameter names (debug, test, hide, source, etc.) and common values (true, yes, on, 1 etc.) to make requests to known app page or function. For POST requests, insert parameter to both URL query string and message body. Burp Intruder can do this using multiple payload set and cluster bomb attack type.
  2. Monitor all responses to identify any anomalies indicating any effect on app’s processing.
  3. Target different pages and functions, most likely to place like login, search, file upload and download etc. where debug logic might be implemented.

ANALYZING APPLICATIONS

The task of analyzing app’s functionality, behavior, and technologies employed to identify the key attack surfaces is also important.

Key areas are:

  • Core functionality
  • Peripheral behavior: off-site links, error messages, administrative and logging functions and redirects.
  • Core security mechanisms: session state, access control, authentication mechanism and supporting logic
  • Everywhere the app processes user-supplied input i.e. URL, query string, POST data, cookies
  • Client side technologies i.e. forms, scripts, thick-client components (Java applets, ActiveX controls and Flash) and cookies.
  • Server side technologies i.e. static & dynamic pages, request params, SSL, web server software, DB interactions, email systems and other backend components.

Entry Points for User Input

  • URL File paths
    • RESTful URLs put parameters where folder names would go.
  • Request Parameters
    • Some non standard parameter formats
      • /dir/file;foo=bar&foo2=bar2
      • /dir/file?foo=bar$foo2=bar2
      • /dir/file/foo%3dbar%26foo2%3dbar2
      • /dir/foo.bar/file
      • /dir/foo=bar/file
      • /dir/file?param=foo:bar
      • /dir/file?data=%3cfoo%3ebar%3c%2ffoo%3e%3cfoo2%3ebar2%3c%2ffoo2%3e
  • Placing payloads within embedded XML data fields may give critical bug like SQLi or path traversal
  • HTTP Headers
    • User-Agent is used to detect small screens and sometimes to modify content to boost search engine rankings. May allow XSS and other injection attacks. Also, may reveal different UI.
    • Apps behind load balancer or proxy may use ‘X-Forwarded-For’ header to identify source & log it.
    • Attacker can add additional headers too which app might process.

Out-Of-band Channels

Finding out of band channel from which app receives data can be difficult and usually requires understanding of wider context of functionality that app implements. Example-

  • Web mail app processes email received via SMTP.
  • Publishing app uses function to retrieve content via HTTP from another server.
  • IDS gathers data using sniffer and presents using web interface.
  • Application providing APIs.

Identifying Server-Side Technologies

  • Banner Grabbing
    • Version information of web server and other component might be disclosed.
    • Web page templates may have version information
    • Custom HTTP headers reveal possible web server software
    • URL query string parameters
  • HTTP Fingerprinting
    • Httprecon uses subtle clues to identify versions, not just banners.
  • Wapplyzer
  • File Extensions – Discloses platform or language
    • asp – Microsoft Active Server Pages
    • aspx – Microsoft ASP.NET
    • jsp – Java Server Pages
    • cfm – Cold Fusion
    • php – PHP language
    • d2w – WebSphere
    • pl – perl language
    • py – python language
    • dll – Compiled native code of C/C++
    • nsf/ntf – Lotus Domino
  • Error Messages
    • Error pages for known and unknown and invalid file extensions
  • Directory names
    • servlet – Java Servlets
    • pls – Oracle AppServer PL/SQL gateway
    • cfdocs/cfide – Cold Fusion
    • SilverStream – SilverStream Web server
    • WebObjects or {function}.woa – Apple WebObjects
    • rails – Ruby on Rails
  • Session Tokens
    • JSESSIONID – Java platform
    • ASPSESSIONID – Microsoft IIS Server
    • ASP.NET_SessionId – Microsoft ASP.NET
    • CFID/CFTOKEN – Cold Fusion
    • PHPSESSID – PHP
  • Third-Party Code components
    • Web app incorporate third party code to implement common functionality i.e. shopping carts, login mechanism etc. It can be open source or purchased. One can download and install to perform source code review or probe for defects in controlled way.

HACKSTEPS for Finding input points and identifying technologies employed:

  1. Identify all entry points for user input i.e. URLs, query string parameters, POST data, cookies, and HTTP headers
  2. Identify query string format; should be some variation on name/value pair.
  3. Identify out-of-bound channels for incoming data to app
  4. View HTTP Server banner.
  5. Check for software identifiers in HTTP header or HTML source code
  6. Run httprint to fingerprint web server
  7. Research software versions for vulnerabilities
  8. Review map of URLs and cookies to identify server side technologies

Identifying Server-Side Functionality

  • Dissecting Requests
    • Review names and values of all parameters being submitted to app in context to functionality
    • Think like programmer, imagine what server-side mechanism is likely being used to implement the behavior.
  • Extrapolating Application Behavior
    • Often application behaves consistently across range of its functionality. So if SQLi is filtered try somewhere else to see what filtering is done. If app obfuscates data, try somewhere original string is returned. Or try to deduce obfuscation scheme.
  • Isolating Unique Application Behavior
    • Note any functionality that diverges from standard appearance, parameter naming or navigation mechanism.
    • Note any functionality that have been added retrospectively i.e. debug functions, CAPTCHA controls, usage tracking and third-party code.
    • It is very much possible that standard defenses of framework might not be applied in such cases.

Mapping the Attack Surface

Identify attack surfaces exposed and possible vulnerabilities associated with each one.

  • Client side validation – Checks may not be replicated on server
  • Database interaction – SQLi
  • File upload/Download – Path traversal, Stored XSS
  • Display of user supplied data – XSS
  • Dynamic redirects – Redirection and Header injection
  • Social networking features – Username enumeration, Stored XSS
  • Login – Username enumeration, Weak passwords, Bruteforce
  • Multistage login – Logic flaws
  • Session state – Predictable tokens, Insecure handling of tokens
  • Access Controls – Horizontal and Vertical PE
  • User impersonation functions – PE
  • Cleartext communications – Session Hijacking, Credential/Sensitive data Sniffing
  • Off-Site Links – Leakage of query string parameters in ‘Referer’
  • Interface to external systems – Shortcuts in handling sessions and/or access controls
  • Error messages – Information leakage
  • E-mail interaction – Email and/or command injection
  • Native code components or interaction – Buffer overflow
  • Third party components – Known vulnerabilities
  • Identifiable web server software – Common config weakness, known software bugs

HACKSTEPS for Identifying functionality and mapping attack surface :

  1. Understand core functionality implemented within app and main security mechanism in use.
  2. Identify all features of apps functionality often associated with common vulnerabilities.
  3. Check third party code against public vulnerability database to determine any known issues.
  4. Formulate plan of attack, based on interesting functionality and serious vulnerability

WEB APPLICATION SECURITY TESTING – 3. WEB COMMUNICATIONS

This notes is for learning/educational purpose only. Use it at your own risks. 

THE HTTP PROTOCOL

The HTTP Protocol is connectionless protocol. Client sends HTTP request to web server, then gets HTTP response. No session is formed, nothing is remembered.

The HTTP Request

The first line of every HTTP request consists of three items, separated by spaces.

  1. Verb indicating HTTP method i.e. GET, POST, PUT, DELETE, OPTIONS, HEAD, TRACE, CONNECT
  2. Requested URL for a particular resource
  3. HTTP Version being used i.e. HTTP/1.0, HTTP/1.1 etc.

Other lines in HEAD part of HTTP request contains other HTTP headers like Host, Referer, User-Agent, Cookie, Connection, Accept, Accept-Encoding etc.

  • The ‘Host’ header – mandatory in HTTP/1.1. It specifies hostname. Essential when multiple hosts run on same IP like in case of virtual hosting.
  • The ‘User-Agent’ header – provides info about browser or client software which generates request.
  • The ‘Referer’ header – contains URL from which request has been originated.
  • The ‘Cookie’ header – contains parameters (name value pairs) that server has issued to client.
  • The ‘Accept’ header – tells server what content client can accept i.e. image types, document formats etc.
  • The ‘Accept-Encoding’ header – tells server what content encoding client can accept.
  • The ‘Authorization’ header – submits credentials to server for HTTP authentication types.
  • The ‘If-Modified-Since’ header – tells when client last received requested resource. If resource is not modified since then client can use cached copy, using response status code 304.
  • The ‘If-None-Match’ header – specifies entity tag, an identifier denoting content of body. The client submits entity tag to server. Server determines with entity tag if client can use cached copy of resource.
  • The ‘Origin’ header – used in cross domain AJAX requests to indicate the domain from which request has originated.

The HTTP Response

The first line contains HTTP version, HTTP response status code, textual ‘phrase’ describing the response.

  • The ‘Server’ header – contains a banner indicating web server software being used. Information may or may not be accurate, often obfuscated due to security reason to prevent information gathering.
  • The ‘Set-Cookie’ header – issues browser a further cookie, this is submitted back in Cookie header of subsequent requests to this server.
  • The ‘Pragma’ header – tells browser not to store response in its cache.
  • The ‘Content-Length’ header – tells length of message body in bytes.
  • The ‘Expires’ header – specifies date & time when the content should expire and resource is re-requested.
  • The ‘Access-Control-Allow-Origin’ header – indicates if resource can be retrieved via cross domain AJAX requests.
  • The ‘Cache-Control’ header – tells caching directives to browser.
  • The ‘Etag’ header – specified an entity tag.
  • The ‘Expires’ header – tells browser how long content of body is valid.
  • The ‘Location’ header – used in redirection responses to specify target of redirect
  • The ‘WWW-Authenticate’ header – used in responses having 401 status code to provide authentication details
  • The ‘X-Frame-Options’ header – indicates whether and how current response may be loaded within browser.

Note: See Chapter 13 for explanation of few headers in relation to cross domain AJAX requests.

HTTP General headers

  • The ‘Connection’ header – tells other host if it should close TCP connection after HTTP transmission or keep it open.
  • The ‘Content-Encoding’ header – tells what encoding is used for content in body i.e. gzip – used by some apps to compress response for faster transmission
  • The ‘Content-Type’ header – tells type of content in message body i.e. text/html, text/xml, text/json etc.

The HTTP Methods

  • GET method for retrieving resources. It can send parameters in URL query string. URL might be logged on server. Never put sensitive information in query string.
  • POST method performs actions. Request parameters can be in URL query string and in body of message. Parameters in body aren’t saved in bookmarks or server logs.
  • HEAD method returns only header not the body. Used to check if resource is available.
  • OPTIONS shows what HTTP method is accepted by web server.
  • PUT uploads to server. Usually disabled, but might be used with APIs.

Cookies

Cookies are resubmitted in each request to same domain by client to server.
Optional attributes are:

  • expires – date when cookie becomes invalid. If not specified, cookie is valid till browser is closed.
  • domain – specified domain for which cookie is valid. This must be same from which cookie is received. “Same-Origin-Policy”
  • path – specifies URL path for which cookie is valid.
  • secure – if it is set, cookie is transmitted only in HTTPS requests.
  • HttpOnly – if it is set, cookie cant be accessed directly by JavaScript.

Status Code Groups

  • 1xx – Informational
  • 2xx – Request was successful.
  • 3xx – Client is redirected to different resource
  • 4xx – Request contains an error of some kind
  • 5xx – Server encountered an error fulfilling the request

Important Status Codes

  • “200 OK” – request succeeded, response body contains result
  • “301 Moved Permanently” – redirects browser to another location, client should use new URL in future
  • “302 Found” – temporary redirect
  • “304 Not Modified” – browser should use cached copy
  • “400 Bad Request” – invalid HTTP request
  • “401 Unauthorized” – requires HTTP authentication, ‘WWW-Authenticate’ tells type of authentication required
  • “403 Forbidden” – no one is allowed to access
  • “404 Not Found” – requested resource does not exist
  • “500 Internal Server Error” – unhandled exception, server side error
  • “503 Service Unavailable” – Web server is responding, but application it serves does not respond

Redirections from HTTP to HTTPS is not okay. One can hijack session and force to use unsecure connection.

Uniform Resource Locator (URL)

 protocol://hostname[:port]/[path/]file[?param=value]
  • If protocol is absent, it defaults to HTTP.
  • If port is absent, it uses default port for protocol i.e. 80 for HTTP, 443 for HTTPS etc.

Representational State Transfer (REST)

  • Architectural style for distributed systems.
  • In REST style, URL contains parameters in URL file path rather than query strong. i.e.
http://wahh.com/search?make=mercedes&model=s-class
  • Corresponds to REST style as:
http://wahh.com/search/mercedes/s-class

HTTP Authentication

HTTP has its own authentication mechanism using various schemes:

  • Basic : User sends credentials as base64 encoded string in request message.
  • NTLM : challenge-response mechanism and uses a version of Windows NTLM protocol
  • Digest : challenge-response mechanism and uses MD5 checksums of nonce with user credentials.

All schemes are cryptographically weak, so it is recommended to use HTTPS.

HTTPS

  • HTTP over SSL (Secure Socket Layer)
  • SSL is actually TLS (Transport Layer Security) now. Original versions of SSL is deprecated.
  • SSL encrypts data while in transit.

HTTP Proxies

  • Browser sends requests to proxy server. Proxy fetches resources and sends back to client.
  • Proxies can provide caching, authentication, and access control.
  • When HTTPS is used, browser cant perform SSL handshake with proxy as it breaks the secure tunnel. Hence browser must use proxy as pure TCP-level relay to pass data between browser and server in both direction. To establish this relay, browser makes HTTP request to proxy with CONNECT method specifying server hostname and port as URL. If proxy allows, it returns 200 OK and keeps TCP connection open.

HTTPS and MITM Attacks

  • HTTPS connections use public-key cryptography. Only endpoints can decrypt traffic.
  • Companies wanting to restrict HTTPS traffic have two choices:
    • Perform complete MITM (Man-In-The-Middle) with fake certificates or real root certificates from trusted CA’s.
    • Allow encrypted traffic to trusted domains without possibility of inspection.

Same Origin Policy

  • A residing on one domain can cause arbitrary request to another domain. But it cannot itself process the data returned from that request.
  • A page residing on one domain can load a script from another domain and execute this within its own context. This is because scripts are assumed to contain code rather than data. So cross domain access should not lead to disclosure of any sensitive information.
  • A page residing on one domain cannot read or modify cookies or other DOM data belonging to another domain.

Web 2.0

  • Heavy use of AJAX for asynchronous requests (behind the scene requests).
  • Increased cross-domain integration using various techniques.
  • Use of new technologies on client side i.e. XML, JSON and Flex.
  • Supports user-generated content, information sharing and interaction.

State and Sessions

Stateful data required to supplement stateless HTTP. This data is held in server-side structure called session. Some state data is stored on client, often cookies or hidden form fields.

ENCODING SCHEMES

URL Encoding:

URLs may contain only printable ASCII characters (0x20 to 0x7e, inclusive). To transfer other characters, characters must be url encoded.
URL encoded form has % prefix followed by character’s two digit ASCII code expressed in hex. i.e.

  • = (%3d)
  • % (%25)
  • Space (%20)
  • New Line (%0a)
  • Null byte (%00)

The + character represents URL encoded space.
Always encode following during web app security testing:

space % ? & = ; + #

Unicode Encoding:

  • Character encoding standard designed to support world’s all writing systems.
  • For using over HTTP, 16-bit Unicode encoding has %u as prefix followed by character’s unicode code point expressed in hexadecimal.
  • UTF-8 is variable length encoding standard employing one or more bytes to express each character. For multibyte character it uses each byte expressed in hexadecimal and preceded by % prefix. i.e.
    Copyright symbol is %c2%a9
  • It can be used sometimes to defeat input validation mechanisms.

HTML Encoding:

HTML entities to represent specific literal characters i.e.

" = “

 

' = ‘

 

& = &

 

&lt; = <

 

&gt; = >

Also, any character can be HTML encoded using its ASCII code in decimal form i.e.

" = "

 

' = '

OR, by using ASCII code in hex i.e.

" = "

 

' = '

HTML encoding user data before sending to another user is used to prevent XSS.

Base64 Encoding:

  • Represents binary data using 64 ASCII characters (A-Za-z0-9/=) using six bits at a time in block of 3 bytes. If final input block results in fewer than 3 chunks of output data, output is padded with one or two = characters.
  • Used to encode email attachments for sending via SMTP.

Hex Encoding:

Hexadecimal representation of each ASCII characters.

WEB APPLICATION SECURITY TESTING – 2. CORE DEFENSE MECHANISMS

This notes is for learning/educational purpose only. Use it at your own risks.

Core elements of defense mechanisms usually employed by Web Applications:

  • Handling user access to app’s data and functionality to prevent unauthorized access
  • Handling user input to prevent malformed input from causing undesirable behavior
  • Handling attackers by taking suitable defensive and offensive measures
  • Administrative monitoring and configuring application

HANDLING USER ACCESS

  • Authentication : Process contains core authentication mechanism, plus authentication related functions. Often it contains defects in both design and implementations.
  • Session Management : Using cookies for tracking user and requests. User is identified with session token. Session management is highly dependent on security of token. Defects in how tokens are generated enables token guessing and defects in how tokens are handled enables attacker to capture other users token.
  • Access Control : To make and enforce correct decisions about whether individual request should be permitted or denied. Due to complex nature of access control requirements it becomes source of security vulnerabilities.

HANDLING USER INPUT

Various types of inputs include arbitrary texts like blog posts, cookies, hidden form fields, parameters and http header fields like user agent.

Input Validation is most common solution. However input validation on client side, often written with JavaScript, can be bypassed.

Approaches to input handling

  • Rejecting Known bad or ‘Blacklisting’
    • Least effective method due to difficulty of identify all bad input.
    • If SELECT is blocked, try SeLeCT
    • If ‘or 1=1–‘ is blocked, try ‘or 2=2–‘
    • If alert(‘xss’) is blocked, try prompt(‘xss’)
  • Accepting Known Good or ‘Whitelisting’
    • Most effective technique
    • Sometimes not feasible in cases where input is blog post or names containing quotes.
  • Sanitization
    • Render dangerous input harmless
    • URL Encoding
    • Difficult is several kinds of data is present within input. So Boundary validation is a better option.
  • Safe Data Handling
    • Code that cant be fooled by malicious input i.e. SQL parameterized queries, not passing input to OS command line.
    • May be impossible to achieve it due to requirement of intensive training for all developers, often settled with devices like WAF etc.
  • Semantic Checks
    • Malicious input is identical to valid input like providing different user id.
    • Data must be validated in context i.e. input user id belongs to logged in user?

Note: In context where NULL bytes act as string delimiter, it can be used to terminate file name or query string. In context where NULL byte is ignored, arbitrary NULL bytes can be used to defeat some black-list based filters.

Problem with Simple Input Validation

  • User input is untrusted
  • Server side app is trusted. Apps may chain several processing steps together. Data may be harmless at one stage but can be harmful at another stage.

Boundary Validation

  • Trust boundary is required.
  • Clean data that passes a boundary
  • Each component treats its input as malicious
  • Data validation should be performed at each trust boundary. Not just between client and server.
  • Example:
    • Username and password is input. Allow only good characters, limits length, remove known attack signatures.
    • Escape dangerous characters in SQL query performing credential verification.
    • App server passes user profile data to SOAP service. XML metacharacters are encoded to block SOAP injection.
    • App displays user account information back to browser. User supplied data is HTML encoded to block XSS known as Output Sanitization.

Simple Filtering Issues:

  • Rejecting ‘<script>’ can be bypassed by ‘<sc<script>ript>’
  • Multistep filtering: First removing ‘../’, then ‘..\’ can be bypassed by ‘….\/’

Canonicalization

Canonicalization is process of converting or decoding data into common character set. If any canonicalization is done after filters have been applied, an attacker may use suitable encoding scheme to bypass validation mechanism.

  • App gets URL-encoded data from browser. To block apostrophe, app filters %27. But data is decoded twice by mistake so app gets %2527 as apostrophe which bypasses app filters.
  • If app strips apostrophe instead of encoding then performs canonicalization then %%2727 can be effective.

Note: Some browsers perform HTML decode of src parameter value. So if encoded input bypasses filters and is passed to app’s response then JavaScript executes. Canonicalization also raises issue when app converts data from one character set to another.

HANDLING ATTACKERS

Attackers are handled by implementing following measures:

  • Handling errors
  • Maintaining audit logs
  • Alerting administrators
  • Reacting to attacks

Handling Errors:

  • Show appropriate error messages
  • Unhandled errors lead to overly-informative error messages

Audit logs:

  • Authentication events like login success or failure, password change etc.
  • Key transactions like credit card payments or fund transfer
  • Access attempts that is blocked by Access control mechanisms
  • Requests containing known attack strings
  • For high security, log every client request in full with IP, time, cookie etc.
  • Store audit log to autonomous system that accepts only update messages from main app
  • Poorly protected log can be gold mine, disclosing sensitive info like session tokens and request parameters.

Alerting Administrators:

  • Use anomalies for alerting, like large number of requests from same IP or user
  • Business anomalies, like large number of fund transfers to/from same account
  • Requests containing known attack strings
  • Requests where hidden data has been modified.
  • WAF can detect generic attacks but not subtle ones.
  • Most effective security control is integrated with app’s input validation mechanisms.

Reacting to Attacks:

  • Attackers probe for vulnerabilities. Sending many similar requests.
  • Automated defenses include responding increasingly slowly to requests or terminating attacker’s session. Like Bro tool does.

MANAGING APPLICATIONS

To manage and monitor applications, administrative interfaces are often built in app itself or accessible through some other interface which may perform user account and roles management, access monitoring and audit functions, perform diagnostics and log management. So it is primary attraction for attacker as vehicle for PE (privilege escalation).

Attacking Admin interfaces:

  • Defeat weak authentication mechanisms
  • Poor implementation of access control mechanisms, provides access to admin functions with low privileges
  • Cookie theft and session hijack with XSS compromises admin level privileges/account

 

WEB APPLICATION SECURITY TESTING – 1. INTRODUCTION

This notes is for learning/educational purpose only. Use it at your own risks.

COMMON WEB APPLICATIONS

Most common Web applications used today are:

  • Shopping (Amazon)
  • Social Networking (Facebook)
  • Banking (CitiBank)
  • Web Search (Google)
  • Web Mail (Gmail)
  • Auctions (Ebay) etc.

Internal Web apps in organizations (Cloud services) are :

  • HR payroll information, performance reviews
  • Admin interfaces to servers, VM’s, workstations
  • Sharepoint, ERP, Outlook Web access, Office apps etc.

WEB APP SECURITY

State of Web app security:

  • Breaches are common. Attackers get sensitive data usually by gaining complete control of back end systems.
  • DoS (Denial of Service) at application level

Common Security flaws:

  • Broken Authentication and Access controls
  • SQL Injection
  • XSS (Cross Site Scripting – User input is script which gets executed in browser)
  • CSRF (Cross Site Request Forgery – Custom link created for execution in different context.)
  • Information Leak

THE FUNDAMENTAL SECURITY ISSUE is that users can supply arbitrary input. Malicious input can compromise site.

  • Alter parameters, cookies, HTTP headers
  • Client side controls cant be trusted
  • Developers must assume all input is malicious
  • Attacker have attack tools like burp, not restricted to use browsers

Scenario: Static Website

Information flows one way. Attacker who exploits web server can steal public data or deface the site.

Scenario: Web Applications

Two way information flow. User logs in and submit content. Lot of data is sensitive and private. Most apps are developed in house. And often developers are naive about security.

Various possible attacks at client side:

  • Change price of item
  • Modify session token to enter another user’s account
  • Remove parameters to exploit logic flaws
  • SQLi

Key Problem Factors for state of security:

  • Underdeveloped security awareness
  • Custom/In-house app development
  • Deceptive simplicity: Easy to make website (using frameworks etc.), but hard to secure it.
  • Rapidly evolving threat profile: Security steps taken at beginning might get outdated.
  • Resource and Time constraints
  • Overextended technologies
  • Increasing demands on functionality

The New Security Perimeter

  • Edge firewalls and bastion hosts are not enough to keep attacker out of critical systems, because user input is custom crafted.
  • Third party components can also have vulnerability which might break your security.
  • Attackers can attack client side controls instead of servers.

Future of Security

  • #1 security measure – updates
  • Some vulnerabilities are decreasing
  • Logic flaws and failure to use controls properly are not decreasing

Example of latest hack in Feb 2018 : SinVR Hack – 20k User credentials & information exposed. Hack was possible due to IDOR (Indirect Object Reference) weakness.