86Web Application Penetration Testingfore vital in the overall security of the application. Being able to tamperwith cookies may result in hijacking the sessions of legitimateusers, gaining higher privileges in an active session, and in generalinfluencing the operations of the application in an unauthorized way.In this test the tester has to check whether the cookies issued to clientscan resist a wide range of attacks aimed to interfere with thesessions of legitimate users and with the application itself. The overallgoal is to be able to forge a cookie that will be considered validby the application and that will provide some kind of unauthorizedaccess (session hijacking, privilege escalation, ...).Usually the main steps of the attack pattern are the following:• cookie collection: collection of a sufficient number of cookie samples;• cookie reverse engineering: analysis of the cookie generationalgorithm;• cookie manipulation: forging of a valid cookie in order to performthe attack. This last step might require a large number of attempts,depending on how the cookie is created (cookie brute-force attack).Another pattern of attack consists of overflowing a cookie. Strictlyspeaking, this attack has a different nature, since here testers are nottrying to recreate a perfectly valid cookie. Instead, the goal is to overflowa memory area, thereby interfering with the correct behavior ofthe application and possibly injecting (and remotely executing) maliciouscode.How to TestBlack Box Testing and ExamplesAll interaction between the client and application should be tested atleast against the following criteria:• Are all Set-Cookie directives tagged as Secure?• Do any Cookie operations take place over unencrypted transport?• Can the Cookie be forced over unencrypted transport?• If so, how does the application maintain security?• Are any Cookies persistent?• What Expires= times are used on persistent cookies, and are theyreasonable?• Are cookies that are expected to be transient configured as such?• What HTTP/1.1 Cache-Control settings are used to protect Cookies?• What HTTP/1.0 Cache-Control settings are used to protect Cookies?Cookie collectionThe first step required to manipulate the cookie is to understand howthe application creates and manages cookies. For this task, testershave to try to answer the following questions:• How many cookies are used by the application?Surf the application. Note when cookies are created. Make a listof received cookies, the page that sets them (with the set-cookiedirective), the domain for which they are valid, their value, and theircharacteristics.• Which parts of the the application generate and/or modify thecookie?Surfing the application, find which cookies remain constant and whichget modified. What events modify the cookie?• Which parts of the application require this cookie in order to beaccessed and utilized?Find out which parts of the application need a cookie. Access a page,then try again without the cookie, or with a modified value of it. Try tomap which cookies are used where.A spreadsheet mapping each cookie to the corresponding applicationparts and the related information can be a valuable output of thisphase.Session AnalysisThe session tokens (Cookie, SessionID or Hidden Field) themselvesshould be examined to ensure their quality from a security perspective.They should be tested against criteria such as their randomness,uniqueness, resistance to statistical and cryptographic analysis andinformation leakage.• Token Structure & Information LeakageThe first stage is to examine the structure and content of a Session IDprovided by the application. A common mistake is to include specificdata in the Token instead of issuing a generic value and referencingreal data at the server side.If the Session ID is clear-text, the structure and pertinent data may beimmediately obvious as the following:http: /foo.bar/showImage?img=img00011If part or the entire token appears to be encoded or hashed, it shouldbe compared to various techniques to check for obvious obfuscation.For example the string “192.168.100.1:owaspuser:password:15:58”is represented in Hex, Base64 and as an MD5 hash:HexBase64MD53139322E3136382E3130302E313A6F77617370757365723A70617373776F72643A31353A3538MTkyLjE2OC4xMDAuMTpvd2FzcHVzZXI6cGFzc3dvcmQ6MTU6NTg=01c2fc4f0a817afd8366689bd29dd40aHaving identified the type of obfuscation, it may be possible to decodeback to the original data. In most cases, however, this is unlikely. Evenso, it may be useful to enumerate the encoding in place from the formatof the message. Furthermore, if both the format and obfuscationtechnique can be deduced, automated brute-force attacks could bedevised.Hybrid tokens may include information such as IP address or User IDtogether with an encoded portion, as the following:owaspuser:192.168.100.1:a7656fafe94dae72b1e1487670148412Having analyzed a single session token, the representative sampleshould be examined. A simple analysis of the tokens shouldimmediately reveal any obvious patterns. For example, a 32 bittoken may include 16 bits of static data and 16 bits of variabledata. This may indicate that the first 16 bits represent a fixed attributeof the user – e.g. the username or IP address. If the second
87Web Application Penetration Testing16 bit chunk is incrementing at a regular rate, it may indicate asequential or even time-based element to the token generation.See examples.If static elements to the Tokens are identified, further samplesshould be gathered, varying one potential input element at a time.For example, log in attempts through a different user account orfrom a different IP address may yield a variance in the previouslystatic portion of the session token.The following areas should be addressed during the single andmultiple Session ID structure testing:• What parts of the Session ID are static?• What clear-text confidential information is stored in the SessionD? E.g. usernames/UID, IP addresses• What easily decoded confidential information is stored?• What information can be deduced from the structure of theSession ID?• What portions of the Session ID are static for the same log inconditions?• What obvious patterns are present in the Session ID as a whole,or individual portions?Session ID Predictability and RandomnessAnalysis of the variable areas (if any) of the Session ID should beundertaken to establish the existence of any recognizable or predictablepatterns. These analyses may be performed manually andwith bespoke or OTS statistical or cryptanalytic tools to deduceany patterns in the Session ID content. Manual checks should includecomparisons of Session IDs issued for the same login conditions– e.g., the same username, password, and IP address.Time is an important factor which must also be controlled. Highnumbers of simultaneous connections should be made in order togather samples in the same time window and keep that variableconstant. Even a quantization of 50ms or less may be too coarseand a sample taken in this way may reveal time-based componentsthat would otherwise be missed.Variable elements should be analyzed over time to determinewhether they are incremental in nature. Where they are incremental,patterns relating to absolute or elapsed time should be investigated.Many systems use time as a seed for their pseudo-randomelements. Where the patterns are seemingly random, one-wayhashes of time or other environmental variations should be consideredas a possibility. Typically, the result of a cryptographichash is a decimal or hexadecimal number so should be identifiable.In analyzing Session ID sequences, patterns or cycles, static elementsand client dependencies should all be considered as possiblecontributing elements to the structure and function of theapplication.• Are the Session IDs provably random in nature? Can the resultingvalues be reproduced?• Do the same input conditions produce the same ID on asubsequent run?• Are the Session IDs provably resistant to statistical orcryptanalysis?• What elements of the Session IDs are time-linked?• What portions of the Session IDs are predictable?• Can the next ID be deduced, given full knowledge of thegeneration algorithm and previous IDs?Cookie reverse engineeringNow that the tester has enumerated the cookies and has a generalidea of their use, it is time to have a deeper look at cookiesthat seem interesting. Which cookies is the tester interested in?A cookie, in order to provide a secure method of session management,must combine several characteristics, each of which isaimed at protecting the cookie from a different class of attacks.These characteristics are summarized below:[1] Unpredictability: a cookie must contain some amount of hardto-guessdata. The harder it is to forge a valid cookie, the harder isto break into legitimate user’s session. If an attacker can guess thecookie used in an active session of a legitimate user, they will beable to fully impersonate that user (session hijacking). In order tomake a cookie unpredictable, random values and/or cryptographycan be used.[2] Tamper resistance: a cookie must resist malicious attemptsof modification. If the tester receives a cookie like IsAdmin=No,it is trivial to modify it to get administrative rights, unless the applicationperforms a double check (for instance, appending to thecookie an encrypted hash of its value)[3] Expiration: a critical cookie must be valid only for an appropriateperiod of time and must be deleted from the disk or memoryafterwards to avoid the risk of being replayed. This does not applyto cookies that store non-critical data that needs to be rememberedacross sessions (e.g., site look-and-feel).[4] “Secure” flag: a cookie whose value is critical for the integrityof the session should have this flag enabled in order to allow itstransmission only in an encrypted channel to deter eavesdropping.The approach here is to collect a sufficient number of instancesof a cookie and start looking for patterns in their value. The exactmeaning of “sufficient” can vary from a handful of samples,if the cookie generation method is very easy to break, to severalthousands, if the tester needs to proceed with some mathematicalanalysis (e.g., chi-squares, attractors. See later for more information).It is important to pay particular attention to the workflow of theapplication, as the state of a session can have a heavy impact oncollected cookies. A cookie collected before being authenticatedcan be very different from a cookie obtained after the authentication.Another aspect to keep into consideration is time. Always recordthe exact time when a cookie has been obtained, when there isthe possibility that time plays a role in the value of the cookie (theserver could use a time stamp as part of the cookie value). Thetime recorded could be the local time or the server’s time stampincluded in the HTTP response (or both).When analyzing the collected values, the tester should try to figureout all variables that could have influenced the cookie value andtry to vary them one at the time. Passing to the server modifiedversions of the same cookie can be very helpful in understandinghow the application reads and processes the cookie.