Working with Sessions and Cookies - web-services

I have this one question in mind that in login sessions does client have to maintain anything so that server uniquely identify client and in multiple client requests response to correct client. I don't understand this sessions and cookies. I asked many about this some say that its server job to maintain sessions and client just send normal request.

Yes, the client must keep track of something, called a session ID. Most commonly, it is a cookie. However, a less used approach is to rewrite all links to pass the session ID in the URL.
Example ID names are ASP.NET_SessionId and PHPSESSID.

Matthew's answer is correct.
It is the server's job to keep track of login sessions, and it's the client web browser's job to keep track of cookies. When you provide username & password on a site, a cookie is provided by the web server to your browser, which will automatically be provided along with subsequent requests to the web server. This cookie uniquely identifies a session which belongs to a particular user on the site (even the "guest" user). So, the server keeps track of all client sessions, and each client remembers its session cookie & provides it along with all its requests. It's a simple scheme. Using Firebug for example, you can see what the web requests look like when you log into a site. You might find that interesting to look at.

It is the server which will maintain the sessions. And it is the server responsibilty to allow session tracking happen. Clients need not bother about sending any information explicitly. As Cliens also sends Cookies saved on the client along with every request, server might use Cookies for sesssion tracking.
Note: Cookies are just one of the way to implement Session Tracking. It is also the best way
So server Cookies as one of the ways to handle session tracking.
It can also be done in other ways:
URL rewriting - the application/server should append the session id in all URL's/Links. When those are invoked from the client the session comes to the server along with the URL.
Hidden Form Fields - The forms may contain hidden input type with session id as field value. When the form is posted, the session id comes along with the form data.

Related

How to protect web application from cookie stealing attack?

My web application's authentication mechanism currently is quite simple.
When a user logs in, the website sends back a session cookie which is stored (using localStorage) on the user's browser.
However, this cookie can too easily be stolen and used to replay the session from another machine. I notice that other sites, like Gmail for example, have much stronger mechanisms in place to ensure that just copying a cookie won't allow you access to that session.
What are these mechanisms and are there ways for small companies or single developers to use them as well?
We ran into a similar issue. How do you store client-side data securely?
We ended up going with HttpOnly cookie that contains a UUID and an additional copy of that UUID (stored in localStorage). Every request, the user has to send both the UUID and the cookie back to the server, and the server will verify that the UUID match. I think this is how OWASP's double submit cookie works.
Essentially, the attacker needs to access the cookie and localStorage.
Here are a few ideas:
Always use https - and https only cookies.
Save the cookie in a storage system (nosql/cache system/db) and set it a TTL(expiry).
Never save the cookie as received into the storage but add salt and hash it before you save or check it just like you would with a password.
Always clean up expired sessions from the store.
Save issuing IP and IP2Location area. So you can check if the IP changes.
Exclusive session, one user one session.
Session collision detected (another ip) kick user and for next login request 2 way authentication, for instance send an SMS to a registered phone number so he can enter it in the login.
Under no circumstances load untrusted libraries. Better yet host all the libraries you use on your own server/cdn.
Check to not have injection vulnerabilities. Things like profiles or generally things that post back to the user what he entered in one way or another must be heavily sanitized, as they are a prime vector of compromise. Same goes for data sent to the server via anything: cookies,get,post,headers everything you may or may not use from the client must be sanitized.
Should I mention SQLInjections?
Double session either using a url session or storing an encrypted session id in the local store are nice and all but they ultimately are useless as both are accessible for a malicious code that is already included in your site like say a library loaded from a domain that that has been highjacked in one way or another(dns poison, complomised server, proxies, interceptors etc...). The effort is valiant but ultimately futile.
There are a few other options that further increase the difficulty of fetching and effectively using a session. For instance You could reissue session id's very frequently say reissue a session id if it is older then 1 minute even if you keep the user logged in he gets a new session id so a possible attacker has just 1 minute to do something with a highjacked session id.
Even if you apply all of these there is no guarantee that your session won't be highjacked one way or the other, you just make it incredibly hard to do so to the point of being impractical, but make no mistake making it 100% secure will be impossible.
There are loads of other security features you need to consider at server level like execution isolation, data isolation etc. This is a very large discussion. Security is not something you apply to a system it must be how the system is built from ground up!
Make sure you're absolutely not vulnerable to XSS attacks. Everything below is useless if you are!
Apparently, you mix two things: LocalStorage and Cookies.
They are absolutely two different storage mechanisms:
Cookies are a string of data, that is sent with every single request sent to your server. Cookies are sent as HTTP headers and can be read using JavaScript if HttpOnly is not set.
LocalStorage, on the other hand, is a key/value storage mechanism that is offered by the browser. The data is stored there, locally on the browser, and it's not sent anywhere. The only way to access this is using JavaScript.
Now I will assume you use a token (maybe JWT?) to authenticate users.
If you store your token in LocalStorage, then just make sure when you send it along to your server, send it as an HTTP header, and you'll be all done, you won't be vulnerable to anything virtually. This kind of storage/authentication technique is very good for Single-page applications (VueJS, ReactJS, etc.)
However, if you use cookies to store the token, then there comes the problem: while token can not be stolen by other websites, it can be used by them. This is called Cross-Site Request Forgery. (CSRF)
This kind of an attack basically works by adding something like:
<img src="https://yourdomain.com/account/delete">
When your browser loads their page, it'll attempt to load the image, and it'll send the authentication cookie along, too, and eventually, it'll delete the user's account.
Now there is an awesome CSRF prevention cheat sheet that lists possible ways to get around that kind of attacks.
One really good way is to use Synchronizer token method. It basically works by generating a token server-side, and then adding it as a hidden field to a form you're trying to secure. Then when the form is submitted, you simply verify that token before applying changes. This technique works well for websites that use templating engines with simple forms. (not AJAX)
The HttpOnly flag adds more security to cookies, too.
You can use 2 Step Authentication via phone number or email. Steam is also a good example. Every time you log in from a new computer, either you'll have to mark it as a "Safe Computer" or verify using Phone Number/Email.

When django session is created

I don't really understand when session is created and per what entity it is created (per ip, per browser, per logged in user). I see in documentation that sessions by default is created per visitor - but what is visitor (browser or ip)?
What are HTTP sessions?
To display a webpage your browser sends an HTTP request to the server, the server sends back an HTTP response. Each time you click a link on website a new HTTP transacation takes place, i.e. it is not a connection that is persistant over time (like a phone call). Your communication with a website consists of many monolitic HTTP transactions (tens or hundres of phonecalls, each phonecall being a few words).
So how can the server remember information about a user, for instance that a user is logged in (ip addresses are not reliable)? The first time you visit a website, the server creates a random string, and in the HTTP response it asks the browser to create a so called HTTP cookie with that value. A cookie is really just a name (of the cookie) and a value. If you go to a simple session-enabled Django site, the server will ask your browser to set a cookie named 'sessionid' with such a random generated value.
The subsequent times your browser will make HTTP requests to that domain, it will include the cookie in the HTTP request.
The server saves these session ids (for django the default is to save in the database) and it saves them together with so called session variables. So based on the session id sent along with an HTTP request it can dig out previously set session variables as well as modify or add session variables. If you delete your cookies (ctrl+shift+delete in Firefox), you will realize that no website remembers you anymore (Gmail, Facebook, Django sites, etc.) and you have to log in again. Most browsers will allow you to disable cookies in general or for specific sites (for privacy reasons) but this means that you can not log into those websites.
Per browser, per window, per tab, per ip?
It is not possible to log into different GMail accounts within the same browser, not even from different windows. But it is possible to log in to one account with Firefox and another with Chrome. So the answer is: per browser. However, it is not always that simple. You can use different profiles in Firefox, and each can keep different cookies and thus you can log into different accounts simultaneously. There are also Firefox plugins for keeping multiple sessions, e.g. MultiFox.
The session all depends on which session cookie your browser sends in it's HTTP request.
Play around
To get the full understanding of what is going on, I recommend installing the FireBug and FireCookie plugins for Firefox. The above screenshots are taken from FireBug's net panel. FireCookie will give you an overview of when and which cookies are set when you visit a site, and will let you regulate which cookies are allowed.
If there is a server side error, and you have DEBUG=True, then the Django error message will show you information about the HTTP request, including the cookies sent
It's browser (not IP). A session is basically data stored on your server that is identified by a session id sent as a cookie to the browser. The browser will send the cookie back containing the session id on all subsequent requests either until the browser is closed or the cookie expires (depending on the expires value that is sent with the cookie header, which you can control from Django with set_expiry).
The server can also expire sessions by basically ignoring the (unexpired) cookie that the browser sends and requiring a new session to be started.
There is a great description on how sessions work here.

What is the difference between a cookie and a session in django?

I think they are same thing but my boss say that is not right. Can someone explain the difference?
A cookie is something that sits on the client's browser and is merely a reference to a Session which is, by default, stored in your database.
The cookie stores a random ID and doesn't store any data itself. The session uses the value in the cookie to determine which Session from the database belongs to the current browser.
This is very different from directly writing information on the cookie.
Example:
httpresponse.set_cookie('logged_in_status', 'True')
# terrible idea: this cookie data is editable and lives on your client's computer
request.session['logged_in_status'] = True
# good idea: this data is not accessible from outside. It's in your database.
A cookie is not a Django, or Python specific technology. A cookie is a way of storing a small bit of state in your client's browser. It's used to supplement (or hack around, depending on your point of view) HTTP, which is a stateless protocol. There are all sorts of limitations here, other domains cant read your cookies, you can only store a a few k of data (just how much depends on the browser!), etc, etc.
A cookie can be used to store a session key. A session is a collection of user state that's stored server side. The session key gets passed back to the server, which allows you to look up that session's state. Most web frameworks (not just Django) will have some sort of session concept built in. This lets you add server-side state to an HTTP conversation.
To complement 'Yuji 'Tomita' Tomita's answer'
with cookies You can set any information on client browser
not just id (session id),
cookies are limited (size limited to kb), less secure and less flexible compared to sessions.
django sessions are based on cookies, django uses a cookie to save session id on client
sessions are not limited to data size (because they are saved on db of server), more secure and more flexible.

Want to understand authorization,cookies,users logins,sessions

I want to understand the logic of authorization,cookies,users logins,sessions..Do you know any source that explain and teach me about it. If it could give any examples it would be great. I mostly use php,jsp but it would be no problem if you give answer related other languages.
The cookie is primarily used to maintain some state on the client side between the requests on a specific domain and/or path. The session is primarily used to maintain some state on the server side between the requests on a specific domain and/or path.
The session is usually backed by a cookie. In PHP it's the cookie with the name PHPSESSID and in JSP it's the cookie with the name JSESSIONID. Both contains a long, unique autogenrated value.
The server side has a mapping between the cookie value and all attached session objects in the memory. On every request, it checks the cookie value in the request header and reveals the attached session objects from the mapping using the cookie value as key. On every response it writes the cookie value to the response header. The client in turn returns it back in the header of the subsequent requests until the cookie is expired.
With regard to authorization/logins, you can put the logged-in User object in the server side session and check on every request if it is there and handle accordingly. On logout you just remove the User object from the session or invalidate the session. In PHP you can access the session by $_SESSION and in Java/JSP by HttpServletRequest#getSession().
The principle is the same in all other web programming languages.

Does an HTTP Session always require a Cookie?

I'm guessing Yes, but I'm not sure.
Both Authenticated Sessions and Anonymous Sessions would reference the stored sessions via the cookie.
########### edit: Clarify
It seems that sessions require some way of referencing for the stored session data.
This reference could be stored in a cookie OR added as a parameter in the URL.
I know this is taking you too literally, but it seemed appropriate to point out that HTTP is stateless and therefore does not have sessions. In order to maintain state, either the browser or the server have to persist the state information between requests. Traditionally, the server maintains the state, and by convention this is called a session, but it has nothing to do with HTTP as it is a workaround. Also, a session usually has a very specific connotation to it - namely that it is an individual visit to the site that will expire when it is no longer being used (some period of inactivity). It will also be different for the same user using different computers or browsers.
In order to achieve a server session, the server will generally set aside some information in memory or database to keep track of state and use a piece of identifying information to associate http requests with that state. This is usually a token. The browser needs to include information identifying the session with each http request. It doesn't matter how this happens, as long as the server and browser agree. It is most often a cookie, or url parameter as fallback, but as long as you set up the code right it could also be part of the url itself, part of a POST body, or even a non-standard http header.
The alternative that is becoming more and more popular is to maintain state in the browser and use purely ajax calls to the server. In this scenario, the server does not have to maintain any concept of session, and will simply return the data that is requested in a completely user-agnostic way. Some authentication may still be needed if the data is private, but a session token is not, and no state is kept on the server.
You can pass the session ID around as a query parameter (www.blah.com/index.php?SESSIONID=fADSF124323). But it has to be on every page. PHP has a option to enable this transparently. It is a huge mess. This is why cookies are preferred.
Not necessarily, some sites use a session ID value present in the URL that represents the session and this value gets appended to all links visited by the user.
We have to use it this way at work, since often mobile browsers don't accept cookies and this is the only way to remember a session.
Also there is HTTP-Authentication, not used often anymore today as the browser has to send username and password to the server unencrypted on every request.
HTTP-Auth just puts username and password in the header sent by your browser.
you can pretty much uniquely identify people by their browser plugins, fonts, etc.
https://panopticlick.eff.org/
When you're using SSL/TLS, then you could at least theoretically use the SSL session id to reference some state on the server.