best practice in managing http-based client sessions

5
An important aspect of correctly manag- ing state information through session IDs relates directly to authentication process- es. While it is possible to insist that a client using an organization's Web appli- cation provide authentication informa- tion for each "restricted" page or data submission, it would soon become tedious and untenable. Thus session IDs are not only used to follow clients throughout the Web application, they are also used to identify each unique, authen- ticated user – thereby indirectly regulat- ing access to site content or information. Maintaining state Typically, the process of managing the state of a Web-based client is through the use of session IDs. Session IDs are used by the application as unique identi- fiers for a client browser, while back- ground (server-side) processes are used to associate the session ID with a level of access. Thus, once a client has been suc- cessfully authenticated to access the Web application, the session ID can be used as a stored authentication voucher so that the end-user does not have to retype their login information with each page request. An organization's application develop- ers have three methods available to them to both allocate and receive session ID information: Session ID information embedded in the URL, which is received by the application through HTTP GET requests when the client clicks on links embedded within a page. Session ID information stored within the fields of a form and submitted to the application. Typically the session ID information would be embedded within the form as a hidden field and submitted with the HTTP POST command. Through the use of cookies. It is important that an organization's sys- tem developers understand the limita- tions and security implications of each delivery mechanism. URL-based session IDs Session ID information embedded in the URL, which is received by the application through HTTP GET requests when the client clicks on links. Example: http://www.example.com/ news.asp?article=27781&sessionID=IE6 0012219 Advantages: Can be used even if the client Web- browser has high security settings and has disabled the use of cookies. Access to the information resource can be sent by the client to other users by providing them with a copy of the URL. If the Session ID is to be permanent- ly associated with the client browser and their computer, it is possible for the client to "Save as a favourite". Depending upon the web browser type, URL information is commonly sent in the HTTP REFERER field. This information can be used to ensure a site visitor has followed a particular path within the Web application, and subsequently used to identify some common forms of attack. Disadvantages: Any person using the same comput- er will be able to review the browser history file or stored favourites and follow the same URL. URL information will be logged by intermediary systems such as fire- walls and proxy servers. Thus anyone with access to these logs could observe the URL and possibly use the information in an attack. It is a trivial exercise for anyone to modify the URL and associated ses- sion ID information within a stan- dard Web browser. Thus, the skills and equipment necessary to carry out the attack are minimal – result- ing in more frequent attacks. When a client navigates to a new website, the URL containing the ses- sion information can be sent to the new site via the HTTP REFERER field. Hidden POST fields Session ID information stored within the fields of a form and submitted to 13 session management Best Practice in Managing HTTP-Based Client Sessions Gunter Ollmann, X-Force Security Assessment Services EMEA, Internet Security Systems Most organizations now have substantial investments in their online Internet pres- ences. For major financial institutions and retailers, the Internet provides both a cost effective means of presenting their offerings to customers, and a method of delivering a personalised 24/7 presence. In almost all cases, the preferred method of delivering these services is over common HTTP. Due to limitations within the protocol, there is no in-built facility to identify or track a particular customer (or session) uniquely within an application. Thus the connection between the cus- tomer’s Web browser and the organisation's Web service is commonly referred to as being "stateless". Because of this, organizations have been forced to adopt custom methods of managing client sessions if they wish to maintain state.

Upload: gunter-ollmann

Post on 05-Jul-2016

214 views

Category:

Documents


2 download

TRANSCRIPT

An important aspect of correctly manag-ing state information through session IDsrelates directly to authentication process-es. While it is possible to insist that aclient using an organization's Web appli-cation provide authentication informa-tion for each "restricted" page or datasubmission, it would soon becometedious and untenable. Thus session IDsare not only used to follow clientsthroughout the Web application, they arealso used to identify each unique, authen-ticated user – thereby indirectly regulat-ing access to site content or information.

Maintaining stateTypically, the process of managing thestate of a Web-based client is throughthe use of session IDs. Session IDs areused by the application as unique identi-fiers for a client browser, while back-ground (server-side) processes are usedto associate the session ID with a level ofaccess. Thus, once a client has been suc-cessfully authenticated to access the Webapplication, the session ID can be usedas a stored authentication voucher sothat the end-user does not have to retypetheir login information with each pagerequest.

An organization's application develop-ers have three methods available to themto both allocate and receive session IDinformation:

• Session ID information embedded inthe URL, which is received by theapplication through HTTP GETrequests when the client clicks onlinks embedded within a page.

• Session ID information stored withinthe fields of a form and submitted tothe application. Typically the sessionID information would be embeddedwithin the form as a hidden field andsubmitted with the HTTP POSTcommand.

• Through the use of cookies.

It is important that an organization's sys-tem developers understand the limita-tions and security implications of eachdelivery mechanism.

URL-based session IDsSession ID information embedded inthe URL, which is received by theapplication through HTTP GETrequests when the client clicks onlinks.

Example: http://www.example.com/news.asp?article=27781&sessionID=IE60012219

Advantages:• Can be used even if the client Web-

browser has high security settingsand has disabled the use of cookies.

• Access to the information resourcecan be sent by the client to otherusers by providing them with a copyof the URL.

• If the Session ID is to be permanent-ly associated with the client browserand their computer, it is possible forthe client to "Save as a favourite".

• Depending upon the web browsertype, URL information is commonlysent in the HTTP REFERER field.This information can be used toensure a site visitor has followed aparticular path within the Webapplication, and subsequently usedto identify some common forms ofattack.

Disadvantages:• Any person using the same comput-

er will be able to review the browserhistory file or stored favourites andfollow the same URL.

• URL information will be logged byintermediary systems such as fire-walls and proxy servers. Thus anyonewith access to these logs couldobserve the URL and possibly usethe information in an attack.

• It is a trivial exercise for anyone tomodify the URL and associated ses-sion ID information within a stan-dard Web browser. Thus, the skillsand equipment necessary to carryout the attack are minimal – result-ing in more frequent attacks.

• When a client navigates to a newwebsite, the URL containing the ses-sion information can be sent to thenew site via the HTTP REFERERfield.

Hidden POST fieldsSession ID information stored withinthe fields of a form and submitted to

13

session management

Best Practice in ManagingHTTP-Based ClientSessionsGunter Ollmann, X-Force Security Assessment Services EMEA,

Internet Security Systems

Most organizations now have substantial investments in their online Internet pres-ences. For major financial institutions and retailers, the Internet provides both acost effective means of presenting their offerings to customers, and a method ofdelivering a personalised 24/7 presence. In almost all cases, the preferred methodof delivering these services is over common HTTP. Due to limitations within theprotocol, there is no in-built facility to identify or track a particular customer (orsession) uniquely within an application. Thus the connection between the cus-tomer’s Web browser and the organisation's Web service is commonly referred to asbeing "stateless". Because of this, organizations have been forced to adopt custommethods of managing client sessions if they wish to maintain state.

the application. Typically the sessionID information would be embeddedwithin the form as a hidden field andsubmitted with the HTTP POSTcommand.

Example: Embedded within theHTML of a page –

<FORM METHOD=POSTACTION=”/cgi-bin/news.pl”><INPUT TYPE=”hidden”NAME=”sessionID”VALUE=”IE60012219”><INPUT TYPE=”hidden”NAME=”allowed” VALUE=”true”><INPUT TYPE=”submit”NAME=”Read News Article”>

Advantages:• Not as obvious as URL embedded

session information, and conse-quently requires a slightly higherskill level for an attacker to carry out any manipulation orhijacking.

• Allows a client to store or transmitURL information relating to the sitesafely without providing access totheir session information.

• Can also be used even if the clientWeb-browser has high security set-tings and has disabled the use ofcookies.

Disadvantages:• While it requires a slightly higher

skill level to perform, attacks can becarried out using commonly avail-able tools such as Telnet or via per-sonal proxy services.

• The Web application page contenttends to be more complex – relyingupon embedded form information,client-side scripting such asJavaScript, or embedded withinactive content such as MacromediaFlash.

• Due to poor coding practices, a fail-ure to check the submission type (i.e.GET or POST) at the server sidemay allow the POST content to bereformed into a URL that could besubmitted via the HTTP GETmethod.

• “Hidden” fields are not really hid-den. While not visible in the HTMLpage rendered in the client browser,they are still visible within theHTML code when viewing thesource.

CookiesEach time a client web browseraccesses content from a particulardomain or URL, if a cookie exists,the client browser is expected to sub-mit any relevant cookie informationas part of the HTTP request. Thuscookies can be used to preserveknowledge of the client browseracross many pages and over periods oftime. Cookies can be constructed tocontain expiry information and maylast beyond a single interactive ses-sion. Such cookies are referred to as"persistent cookies", and are storedon the client browser's hard-drive in alocation defined by the particularbrowser or operating system (e.g.c:\documents and settings\client-name\cookies for Internet Exploreron Windows XP). By omitting expi-ration information from a cookie, theclient browser is expected to store thecookie only in memory. These "ses-sion cookies" should be erased whenthe browser is closed.

Example: Within the plain text of theHTTP server response –

Set-Cookie:sessionID=”IE60012219”; path=”/”;domain=”www.example.com”;expires=”2003-06-0100:00:00GMT”; version=0;secure=yes

Advantages:• Careful use of persistent and session

type cookies can regulate access tothe Web application over time.

• More options are available for con-trolling session ID timeouts.

• Session information is unlikely tobe recorded by intermediarydevices.

• Cookie functionality is built intomost browsers. Thus no special cod-ing is required to ensure session IDinformation is embedded within thepages served to the client browser.

• Inbuilt ability to restrict the submis-sion of cookie information to secure channels (HTTPS) only through theuse of "secure=yes".

Disadvantages:• An increasingly common security

precaution with Web browsers is todisable cookie functionality. ThusWeb applications dependant uponthe cookie function will not work for"security conscious" users.

• As persistent cookies exist as text fileson the client system, they can be eas-ily copied and used on other systems.Depending on the host's file accesspermissions, other users of the hostmay steal this information andimpersonate the user.

• Cookies are limited in size, and areunsuitable for storing complex arraysof state information.

• Cookies contain a "domain" ele-ment. Thus, a request for any filewithin the domain will result in acopy of the cookie being sent.

The session IDAn important aspect of managing statewithin the Web application is the"strength" of the session ID itself. As thesession ID is often used to track anauthenticated user through the applica-tion, organizations must be aware that thesession ID must fulfil a particular set ofcriteria if it is not to be compromisedthrough predictive or brute-force typeattacks. The two critical characteristics ofa good session ID are randomness andlength.

Session ID randomnessIt is important that the session ID isunpredictable and the application utilisesa strong method of generating randomIDs. It is vital that a cryptographicallystrong algorithm is used to generate aunique session ID for an authenticated

14

session management

user. Ideally the session ID should be arandom value. Do not use linear algo-rithms based upon predictable variablessuch as date, time and client IP address.To this end, the session ID should fulfilthe following criteria:

• It must look random – i.e. it shouldpass statistical tests of randomness.

• It must be unpredictable – i.e. itmust be infeasible to predict whatthe next random value will be, given complete knowledge of thecomputational algorithm or hard-ware generating the ID and all pre-vious IDs.

• It cannot be reliably reproduced – i.e.if the ID generator is used twice withexactly the same input criteria, theresult will be an unrelated random ID.

Session ID length It is important that the session ID is ofa sufficient length to make it infeasiblethat a brute force method could be usedsuccessfully to derive a valid ID withina usable timeframe. Given currentprocessor and bandwidth advances, ses-sion IDs consisting of over 50 randomcharacters in length are recommended –but make them longer if the opportuni-ty exists, dependant upon a number offactors:

• Speed of connection – i.e. there aretypically big differences betweenInternet client, B2B and internal net-work connections. While an Internetclient will typically have less than a512 kbps connection speed, an inter-nal user may be capable of connectingto the application server 200 timesfaster. Thus an internal user couldpotentially obtain a valid session IDusing brute force guessing techniquesin 1/200th of the time.

• Complexity of the ID – i.e. what val-ues and characters are used within thesession ID? Moving from numeric val-ues (0-9) to a case-sensitive, alpha-numeric (a-z, A-Z, 0-9) range meansthat, for the same character length,the session ID becomes much moredifficult to predict.

Session hijackingAs session IDs are used to identify andtrack each unique user of a Web applica-tion, any attacker who obtains thisunique identifier is potentially able tosubmit the same information and imper-sonate someone else. This class of attackis commonly referred to as Sessionhijacking. Given the inherent statelessnature of the HTTP (and HTTPS) pro-tocol, the process of masquerading as analternative user with a hijacked sessionID is trivial.

An attacker has at his/her disposal threemethods for gaining session ID informa-tion – observation, brute force and misdi-rection of trust.

ObservationBy default all HTTP traffic crosses thewire in an unencrypted, plain text,mode. Thus, any device with access tothe same wire or shared network devicesis capable of "sniffing" the traffic andrecording session ID information (notto mention user authentication infor-mation such as user names and pass-words). In addition, many perimeterdevices automatically log aspects ofHTTP traffic – in particular the URLinformation.

A simple security measure to prevent"sniffing" or logging of confidential URLinformation is to use the encrypted formof HTTP – HTTPS.

Brute forceIf the session ID information is generat-ed or presented in such a way as to bepredictable, it is very easy for an attack-er to repeatedly attempt to guess a validID. Depending upon the randomnessand the length of the session ID, thisprocess can take as little time as a fewseconds.

In ideal circumstances, an attackerusing a domestic DSL line can potentiallyconduct up to as many as 1000 session IDguesses per second. Thus it is very impor-tant to have a sufficiently complex andlong session ID to ensure that any likelybrute force attack will take many hun-dreds of hours to predict.

Misdirected trustIn ideal circumstances, a client’s Webbrowser would only ever disclose confi-dential session ID information to a single,trusted site. Unfortunately, there arenumerous instances when this is not thecase. For example, the HTTP REFERERfield will send the full URL, and in someapplications this URL may contain ses-sion ID information.

Another popular method, utilisingcommon trust relationship flaws, areHTML embedded and Cross-siteScripting (CSS or sometimes XSS)attacks. Through clever embedding ofHTML code or scripting elements, it ispossible to steal session ID information –even if it is held within the URL, POSTfields and cookies. The author's paper,"HTML Code Injection and Cross-sitescripting"1 has more detail about thisclass of attack.

Common failingsWhile Web-based session management isimportant for tracking users and theirnavigation throughout an application,their most critical use is to maintain thestate information of an authenticated useras he carries out his allowed functions.For online banking and retail environ-ments, using an appropriately strong ses-sion management method is crucial to thesuccess of the application.

The author has had the opportunity toinvestigate session handling techniquesfor many clients' business critical onlineapplications. Based upon these investiga-tions, this section details some of themost common failings and assumptionsthat have been made.

Predictable session ID’sThe most common flaw in session IDusage has always been predictability. Asdiscussed earlier, the two causes are a lackof randomness, or length, or both.

• Sequential allocation of Session IDsEach visitor to the site is allocated asession ID in sequential order. Thus,by observing your own session IDinformation, the simple practice of

session management

15

replacing it with another value a fewiterations up or down will allow theattacker to impersonate anotheruser.

• Session ID values are too shortThe full range of valid session IDscould be covered during an automat-ed attack before there is time for thesession to expire.

• Common hashing techniques While many commercial Web ser-vices have built in functions for cal-culating hashed information, thesemechanisms are well known andavailable for reproduction. A hash-ing function will indeed create a ses-sion ID value that appears to beunique and great care should betaken to ensure that predicableinformation is not used in the gener-ation of the hash.

• Session obfuscationThe use of a custom method ofobscuring data and using it for sessionmanagement. It is never a sound ideato include client or other confidentialinformation within a session ID.

Insecure transmissionFor banking and retailing applications itis crucial that all confidential materialand session information be transmittedsecurely and not vulnerable to observa-tion or replay attacks. Unfortunatelymany commercial packages have failed inthe past to secure the integrity of theirsession management due to insecuretransmission.

• Use encryption when sending sessioninformation – As mentioned earlier,there are a lot of instances whereby auser's connection to the applicationserver will be logged if not sent overan encrypted channel, such asHTTPS. This is particularly impor-tant for applications that require ahigh degree of confidentiality.

• Use different session IDs when shift-ing between secure and insecureapplication components – As a newuser navigates the Web application asa "guest", use a different session ID to

what would be allocated in the securepart of the application. Never use the same session ID information in the authenticated and unauthenti-cated sections of the Web application.Again, ensure that the session ID to be used in the secure part of the Web application is not pre-dictable and based on the previousID.

• Be aware of "domain" trusts – Whenusing cookies, organizations must bevery careful about the effects of the"domain" setting within the cookies.Every client request for data and filesfrom the application server withinthat domain will include a copy of thecookie information. A common prob-lem occurs when a single Web serversupports the application over HTTPand HTTPS. If the application recy-cles common graphics between theHTTP and HTTPS parts of the site,secure session ID information may beinadvertently sent over an insecurechannel (HTTP). The best mecha-nism for stopping this from happen-ing is to split the application betweentwo host servers. One server (e.g.www.example.com) only supportsHTTP while the second (e.g.secure.example.com) only supportsHTTPS. The session ID cookie would then include specificdomain restrictions (e.g.domain="secure. example.com"instead of domain=". example.com").In addition, most Web servers support the use of the cookie “secure”variable. Setting this to "yes" (e.g."secure=yes") will result in the cookieonly ever being sent over a secureHTTPS connection. However, in thepast there have been issues with bothWeb servers and client browsers notcorrectly implementing this method.

Length of Session validityFor secure applications all session infor-mation should be time limited and allowfor client-side cancellation or server-siderevocation.

• Client cancellation – Many Webapplications fail to allow for client-side cancellation such as "log-out". Ifthe intention is to allow users to inter-act with the application from any-where, including Internet cafes,organizations need to be aware thatother users can use the same machineand trawl through the "history" andcached page information. If the ses-sion has not been cancelled, it is atrivial exercise for the next user of thecomputer to "resume" the last connection.

• Session timeout – Again, when deal-ing with the possibility of sharedclient computers, it is extremelyimportant that there is a limited life-time (or period of inactivity) afterwhich the session will automaticallyexpire. The expiry time should bekept to a minimum period, and isdependant upon the nature of theapplication. Ideally the applicationshould be capable of monitoring theperiod of inactivity for each sessionID and be able to delete or revoke thesession ID when a threshold has beenreached.

• Server revocation – In some circum-stances it may be necessary to cancel asession at the server-side. Likelyevents include when the user leavesthe insecure part of the applicationand enters the secure part with a newsession ID. Alternatively, should somekind of attack be recorded by the serv-er, it would be advisable to revoke thesession associated with the attacker'ssystem.

Session verificationThe processes for handling and manip-ulating session ID information must berobust and capable of correctly han-dling attacks targeting the contentwithin. • Session ID Length – Ensure that the

content of the session ID is of theexpected size and type, and that thequality of the information is verifiedbefore processing. For instance, becapable of identifying over-sized

16

session management

session IDs that may constitute abuffer overflow type attack.

• Source of the Session ID – Whenusing the HTTP POST method forcommunication session information,ensure that the application is capableof discerning whether the session IDwas delivered to the application fromthe client browser through the HTTPPOST method, and not through amanipulated GET request.

Storing unique dataWhile it is possible to store a tremen-dous amount of data within the clientbrowser through the use of cookies, hid-den fields and URL information, bestsecurity practice would dictate only

having the minimum set. In this case,just the session ID information — every-thing else should be stored at the appli-cation server end. Once a user hasauthenticated to the application, there isno need for any personal information(such as user name, account number, IPaddress etc.) to be sent over HTTP orHTTPS, unless the application specifi-cally requires the user to change or verifythe information.

Final noteWhile this review has described the limi-tations of various session handling meth-ods, developers must be aware that goodsession management is only one compo-nent of building a secure application.

Good session management can bebypassed through other poorly coded andimplemented application components,and should not be seen as a stand-alonesecurity measure.

References1“HTML Code Injection and Cross-sitescripting”, Gunter Ollmann, InternetSecurity Systems, November 2002

About the authorGunter Ollmann is the EMEA managerof X-Force Security Assessment Servicesfor Internet Security Systems, responsiblefor security assessments, penetration test-ing and vulnerability research. He holdsdegrees in physics and mathematics.

17

defence in depth

Indeed, as happens all too often in IT,the phrase has rapidly become such acliché that we could be forgiven forthinking that defence in depth is alreadyan established part of the IT firmament.The truth is it is still only a pipe dreambecause vendors of the requisite compo-nents are not talking sufficiently to eachother. There may be open or de facto stan-dards for integration, but only at relative-ly low levels, such as specifying howinformation is stored and communicated.Such low level interaction is of courseessential, but true defence in depthrequires a high level understanding

between products and components sothat security is reinforced at each layer,eliciting multiple actions appropriate tothe situation. It should be akin to physi-cal building security, where detection ofan intruder might trigger several simulta-neous and co-ordinated responses, suchas sounding an alarm, alerting securitypersonnel, and locking inner doors pro-tecting critical resources.

One of the problems in IT security isthe number of competing approaches oreven philosophies for tackling parts ofthe problem. There are different types ofkey systems, and varying strategies for

intrusion detection. For anti-virus pack-ages there is the ongoing debate betweenheuristic methods capable of identifyingpreviously unknown agents on the basisof their activity, and pattern matchingapproaches that recognize known virusesfrom databases of their signature. It isbest to combine both methods, just asthe human immune system does againstbiological viruses. But as in the biologi-cal analogue, the action is most effectiveif properly co-ordinated, so that theoverall system “knows” what is going on.

It goes without saying then that youcannot buy a single platform for Defencein Depth. It is a strategy rather than aproduct, and is best implemented in atop down approach starting with a secu-rity policy that recognizes the key highlevel interacting components. These are:

• Logical — embracing the high levelonline protection objectives such asaccess control, encryption, and filter-ing at firewall points.

• Physical — measures to debar unau-thorized access by people to machinerooms and critical network compo-nents such as routers.

• Technical — the techniques used tosupport other components such asphysical and logical. These may

IT networks may seem highly distributed, yet their great weakness is that in realitythey depend on relatively few critical resources. For individual enterprise networksthis means that critical services and information are both vulnerable to co-ordinatedattacks on just a few core components such as application servers and databases.The concept of defence in depth has emerged as a model to insulate these keyresources with protective layers whose interaction ensures that the total level of pro-tection is considerably greater than the sum of its parts.

Defence in depth - protecting the queenPhilip Hunter