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
- 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
- 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.
- 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)
- Login as several users at different times. Similar usernames or email addresses. Record tokens. Analyze tokens for correlations and look for encoding or obfuscation.
- Repeating letters produce repeating encoded characters if XOR is used.
- Use patterns found to try guessing tokens of other users.
- 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.
Attacker can sometime tamper token’s values without decrypting.
- 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
- 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
Categories: Web Application Security Testing