session and cookie management in.net justin brunelle cs795 6/18/2009
TRANSCRIPT
Introduction to Cookies
• Used to store data– Stateful way of storing data in stateless
environment
• Contain two attributes– names and values
Cookie Example
• Creating a cookie in ASP .NET:HttpCookie cookie = new HttpCookie(“cookieName”);
cookie.Values[“ValueName1”] = “MyVal1”;
cookie.Values[“ValueName2”] = “MyVal2”;
• Retrieving a cookie in ASP .NETHttpCookie myCookie = Request.Cookies[“cookieName”];
if(myCookie != null)
{
string val1 = myCookie .Values[“ValueName1”];
string val2 = myCookie .Values[“ValueName2”];
}
Introduction to Sessions
• ASP starts a session and returns a cookie– Automatic when using sessions
• on user login
– Needs cookies
• Session Objects contain session state data
Session Example
• Add data to a session objectSession[“DataName’] = myData;
• Retrieving data from a session objectmyData = Session[“DataName”]
• Other Functions:Session.IsNewSession
Session.RemoveAll
Session.SessionID
Sessions without Cookies
• You don't have to change anything in your ASP.NET application to enable cookieless sessions, except the following configuration setting– <sessionState
cookieless="true" />
• Session identifiers stored in the URL
• Session information lost between sessions with cookieless sessions
•Cookieless sessions creates a security issue when sending URLs to others
http://msdn.microsoft.com/en-us/library/aa479314.aspx
Session Variables
• Can be used to store data about the current user and his session
• Session["FirstName"] = FirstNameTextBox.Text; Session["LastName"] = LastNameTextBox.Text;
Cookies and Security
• Insecure– Stored in text– Can be encrypted
• Still can be read, and possibly decoded
• Solution:– Encrypt in web.config
• <forms protection=“Encryption” />• Use timeouts to prevent theft and reuse
Cookie Poisoning
• Cookies intercepted when sent between the server and the client
• Modifying cookies to gain access to sensitive information– Such as, getting a cookie and changing the
values– Extracting passwords
• Both done with a web proxy tool
http://searchsoftwarequality.techtarget.com/expert/KnowledgebaseAnswer/0,289625,sid92_gci1210580,00.html
Prevent Cookie Poisoning
• Treat cookies as untrusted sources of information
• Use regular expressions and type matching to test validity of cookies– Use regular expressions and strict data
formatting conventions in your code– If the type stored in a cookie is known, make
sure the value of the cookie can be cast • such as string to int, where int is the desired type
Protection from JavaScript and Cookies
• Users can use scripting attacks by entering JavaScript into forms fields– Can be stored in cookies
and read later
• We can cache malicious attacks– Attacks cached from
Cookies, QueryString and Forms Posts.
http://msdn.microsoft.com/en-us/library/ms972967.aspx
Protection from JavaScript and Cookies
• <%@ Page validateRequest=“true" %> – Checks all input data against a list of
potentially dangerous values– Slows performance, but only for users doing
the attack• ValdidateRequest=true won't hamper your users
experience in any way
• HttpRequestValidationException is thrown to signal malicious code– Catch the error and program accordingly
Alternate script injection protection
• Server.HtmlEncode(string)– Encodes the inserted script using html codes– <script
language=“javascript”>alert(“hi”);</script> becomes
– < script > language=" javascript" >alert(" hi" );</script>
– Must be careful about how we use decoded strings with this method
Encrypting Cookies• Use HttpSecureCookie and MachineKeyCryptographyFunction secureMyCookie(HttpCookie myCookie){HttpCookie encodedCookie = new HttpCookie(myCookie.Name,
myCookie.Value); encodedCookie .Domain = myCookie.Domain; encodedCookie .Expires = myCookie.Expires;encodedCookie .HttpOnly = myCookie.HttpOnly;encodedCookie .Path = myCookie.Path;encodedCookie .Secure = myCookie.Secure; encodedCookie.Value = MachineKeyCryptography.Encode(cookie.Value,
CookieProtection cookieProtection);
return encodedCookie; }
http://www.codeproject.com/KB/web-security/HttpSecureCookie.aspx
Encryption and Decryption
• HttpCookie cookie = new HttpCookie("UserName", "Terminator"); cookie.Expires = DateTime.Now.AddDays(1); HttpCookie encodedCookie = HttpSecureCookie.Encode(cookie); Response.Cookies.Add(encodedCookie);
• HttpCookie cookie = Request.Cookies["UserName"]; lblDisplayBefore.Text = cookie.Value; HttpCookie decodedCookie = HttpSecureCookie.Decode(cookie);
Session State in IE Tabs
• Session only shared between tabs if user opens a new tab from a tab already in the session– State can become unstable if user modifies
the same data a different way in each tab– User might have to log into each of the tabs
Resolutions
• Issues with these:– Logging in is annoying– Can’t use pop-ups to transmit data
• Don’t have sessions
– Hidden fields are insecure
• Problem stems from the process that runs the tabs
Resolutions (cont’d)
• Config Setting:<sessionState mode=“InProc” cookieless=“UseURI” />
• Appends the session state to the URL of the new tabhttp://hostName/SamplePage/(S(asdf34qwer10asdfz))/myPage.aspx
– Gives us a new session for each tab stemming from the first session
IE8 Tabs
• Tabs run by one process– Tab process handles a single session for
each tab– Code from the previous slide forces a new
session• Users can also select “File -> New Session”
Tricking ASP .NET Sessions
• Normally, session cookies expire at the end of the session
• We can enter JavaScript in the address bar to create your own session cookies:
javascript:void(document.cookie="ASP.NET_SessionId=WhyDidTheChickenCr
ossThe;path=/") • We can set the expiration date to save the
cookie and session datajavascript:void(document.cookie="ASP.NET_SessionId=WhyDidTheCh
ickenCrossThe;path=/;expires=Mon, 19 Mar 2007 18:25:19 GMT");
Protecting Session Cookies
• ASP .NET does not put login credentials in session cookies– Mitigates the following problem slightly
• Hijackers can still take session cookies and reuse them to gain access to information
• Use the following to protect your cookies:if (!Page.User.Identity.IsAuthenticated)
{if (Page.Request.Cookies["ASP.NET_SessionId"] != null){Response.Cookies["ASP.NET_SessionId"].Expires = DateTime.Now.AddYears(-30);}Session.Abandon();}