<p>Specifically this is regarding when using a client session cookie to identify a session on the server.</p>

<p>Is the best answer to use SSL/HTTPS encryption for the entire web site, and you have the best guarantee that no man in the middle attacks will be able to sniff an existing client session cookie?</p>

<p>And perhaps second best to use some sort of encryption on the session value itself that is stored in your session cookie?</p>

<p>If a malicious user has physical access to a machine, they can still look at the filesystem to retrieve a valid session cookie and use that to hijack a session?</p>

[{'answer_id': 22887, 'author': 'Julio César', 'author_id': 2148, 'author_profile': 'https://Stackoverflow.com/users/2148', 'pm_score': 0, 'selected': False, 'text': '<p>To reduce the risk you can also associate the originating IP with the session. That way an attacker has to be within the same private network to be able to use the session.</p>\n\n<p>Checking referer headers can also be an option but those are more easily spoofed.</p>\n'}, {'answer_id': 22913, 'author': 'Josh Hinman', 'author_id': 2527, 'author_profile': 'https://Stackoverflow.com/users/2527', 'pm_score': 8, 'selected': True, 'text': '<p>Encrypting the session value will have zero effect. The session cookie is already an arbitrary value, encrypting it will just generate another arbitrary value that can be sniffed.</p>\n\n<p>The only real solution is HTTPS. If you don\'t want to do SSL on your whole site (maybe you have performance concerns), you might be able to get away with only SSL protecting the sensitive areas. To do that, first make sure your login page is HTTPS. When a user logs in, set a secure cookie (meaning the browser will only transmit it over an SSL link) in addition to the regular session cookie. Then, when a user visits one of your "sensitive" areas, redirect them to HTTPS, and check for the presence of that secure cookie. A real user will have it, a session hijacker will not.</p>\n\n<p><strong>EDIT</strong>: This answer was originally written in 2008. It\'s 2016 now, and there\'s no reason not to have SSL across your entire site. No more plaintext HTTP!</p>\n'}, {'answer_id': 24445, 'author': 'Community', 'author_id': -1, 'author_profile': 'https://Stackoverflow.com/users/-1', 'pm_score': 5, 'selected': False, 'text': '<p>The SSL only helps with sniffing attacks. If an attacker has access to your machine I will assume they can copy your secure cookie too.  </p>\n\n<p>At the very least, make sure old cookies lose their value after a while. Even a successful hijaking attack will be thwarted when the cookie stops working. If the user has a cookie from a session that logged in more than a month ago, make them reenter their password. Make sure that whenever a user clicks on your site\'s "log out" link, that the old session UUID can never be used again. </p>\n\n<p>I\'m not sure if this idea will work but here goes: Add a serial number into your session cookie, maybe a string like this:</p>\n\n<p>SessionUUID, Serial Num, Current Date/Time</p>\n\n<p>Encrypt this string and use it as your session cookie. Regularly change the serial num - maybe when the cookie is 5 minutes old and then reissue the cookie.  You could even reissue it on every page view if you wanted to. On the server side, keep a record of the last serial num you\'ve issued for that session.  If someone ever sends a cookie with the wrong serial number it means that an attacker may be using a cookie they intercepted earlier so invalidate the session UUID and ask the user to reenter their password and then reissue a new cookie.</p>\n\n<p>Remember that your user may have more than one computer so they may have more than one active session. Don\'t do something that forces them to log in again every time they switch between computers.</p>\n'}, {'answer_id': 24446, 'author': 'Kibbee', 'author_id': 1862, 'author_profile': 'https://Stackoverflow.com/users/1862', 'pm_score': 2, 'selected': False, 'text': "<p>Ensure you don't use incremting integers for session IDs.  Much better to use a GUID, or some other long randomly generated character string.</p>\n"}, {'answer_id': 313873, 'author': 'Hubert', 'author_id': 29525, 'author_profile': 'https://Stackoverflow.com/users/29525', 'pm_score': 3, 'selected': False, 'text': '<p>Try Secure Cookie protocol described in <a href="http://www.cse.msu.edu/~alexliu/publications/Cookie/cookie.pdf" rel="noreferrer">this</a> paper by Liu, Kovacs, Huang, and Gouda:</p>\n\n<p>As stated in document:</p>\n\n<blockquote>\n  <p>A secure\n  cookie protocol that runs between a client and a server\n  needs to provide the following four services: authentication, confidentiality, integrity and anti-replay.</p>\n</blockquote>\n\n<p>As for ease of deployment:</p>\n\n<blockquote>\n  <p>In terms of efficiency, our protocol does not involve any database\n  lookup or public key cryptography. In terms of deployability, our protocol can be easily deployed on an existing web server, and it does not require any change to\n  the Internet cookie specication.</p>\n</blockquote>\n\n<p>In short: it is secure, lightweight, works for me just great.</p>\n'}, {'answer_id': 6532807, 'author': 'Nima', 'author_id': 822755, 'author_profile': 'https://Stackoverflow.com/users/822755', 'pm_score': -1, 'selected': False, 'text': "<p>Protect by:</p>\n\n<pre><code>$ip=$_SERVER['REMOTE_ADDER'];\n$_SESSEION['ip']=$ip;\n</code></pre>\n"}, {'answer_id': 6566332, 'author': 'Nathan', 'author_id': 827372, 'author_profile': 'https://Stackoverflow.com/users/827372', 'pm_score': 4, 'selected': False, 'text': '<p>Have you considered reading a book on PHP security? Highly recommended.</p>\n\n<p>I have had much success with the following method for non SSL certified sites.</p>\n\n<ol>\n<li><p>Dis-allow multiple sessions under the same account, making sure you aren\'t checking this solely by IP address. Rather check by token generated upon login which is stored with the users session in the database, as well as IP address, HTTP_USER_AGENT and so forth</p></li>\n<li><p>Using Relation based hyperlinks\nGenerates a link ( eg. <a href="http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8" rel="nofollow noreferrer">http://example.com/secure.php?token=2349df98sdf98a9asdf8fas98df8</a> )\nThe link is appended with a x-BYTE ( preferred size ) random salted MD5 string, upon page              redirection the randomly generated token corresponds to a requested page. </p>\n\n<ul>\n<li>Upon reload, several checks are done. </li>\n<li>Originating IP Address</li>\n<li>HTTP_USER_AGENT </li>\n<li>Session Token</li>\n<li>you get the point.</li>\n</ul></li>\n<li><p>Short Life-span session authentication cookie.\nas posted above, a cookie containing a secure string, which is one of the direct references to the sessions validity is a good idea. Make it expire every x Minutes, reissuing that token, and re-syncing the session with the new Data. If any mis-matches in the data, either log the user out, or having them re-authenticate their session.</p></li>\n</ol>\n\n<p>I am in no  means an expert on the subject, I\'v had a bit of experience in this particular topic, hope some of this helps anyone out there.  </p>\n'}, {'answer_id': 19726572, 'author': 'Alexandru', 'author_id': 2750086, 'author_profile': 'https://Stackoverflow.com/users/2750086', 'pm_score': 4, 'selected': False, 'text': "<p>There is no way to prevent session hijaking 100%, but with some approach can we reduce the time for an attacker to hijaking the session.</p>\n\n<p>Method to prevent session hijaking:</p>\n\n<p>1 - always use session with ssl certificate;</p>\n\n<p>2 - send session cookie only with httponly set to true(prevent javascript to access session cookie)</p>\n\n<p>2 - use session regenerate id at login and logout(note: do not use session regenerate at each request because if you have consecutive ajax request then you have a chance to create multiple session.)</p>\n\n<p>3 - set a session timeout</p>\n\n<p>4 - store browser user agent in a $_SESSION variable an compare with $_SERVER['HTTP_USER_AGENT'] at each request</p>\n\n<p>5 - set a token cookie ,and set expiration time of that cookie to 0(until the browser is closed).\nRegenerate the cookie value for each request.(For ajax request do not regenerate token cookie).\nEX:</p>\n\n<pre><code>    //set a token cookie if one not exist\n    if(!isset($_COOKIE['user_token'])){\n                    //generate a random string for cookie value\n        $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));\n\n        //set a session variable with that random string\n        $_SESSION['user_token'] = $cookie_token;\n        //set cookie with rand value\n        setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);\n    }\n\n    //set a sesison variable with request of www.example.com\n    if(!isset($_SESSION['request'])){\n        $_SESSION['request'] = -1;\n    }\n    //increment $_SESSION['request'] with 1 for each request at www.example.com\n    $_SESSION['request']++;\n\n    //verify if $_SESSION['user_token'] it's equal with $_COOKIE['user_token'] only for $_SESSION['request'] &gt; 0\n    if($_SESSION['request'] &gt; 0){\n\n        // if it's equal then regenerete value of token cookie if not then destroy_session\n        if($_SESSION['user_token'] === $_COOKIE['user_token']){\n            $cookie_token = bin2hex(mcrypt_create_iv('16' , MCRYPT_DEV_URANDOM));\n\n            $_SESSION['user_token'] = $cookie_token;\n\n            setcookie('user_token', $cookie_token , 0 , '/' , 'donategame.com' , true , true);\n        }else{\n            //code for session_destroy\n        }\n\n    }\n\n            //prevent session hijaking with browser user agent\n    if(!isset($_SESSION['user_agent'])){\n        $_SESSION['user_agent'] = $_SERVER['HTTP_USER_AGENT'];\n    }\n\n    if($_SESSION['user_agent'] != $_SERVER['HTTP_USER_AGENT']){\n      die('session hijaking - user agent');\n    }\n</code></pre>\n\n<p>note: do not regenerate token cookie with ajax request\nnote: the code above is an example.\nnote: if users logout then the cookie token must be destroyed as well as the session</p>\n\n<p>6 - it's not a good aproach to use user ip for preventing session hijaking because some users ip change with each request. THAT AFFECT VALID USERS</p>\n\n<p>7 - personally I store session data in database , it's up to you what method you adopt</p>\n\n<p>If you find mistake in my approach please correct me. If you have more ways to prevent session hyjaking please tell me.</p>\n"}, {'answer_id': 20361967, 'author': 'theironyis', 'author_id': 3063333, 'author_profile': 'https://Stackoverflow.com/users/3063333', 'pm_score': 4, 'selected': False, 'text': '<pre><code>// Collect this information on every request\n$aip = $_SERVER[\'REMOTE_ADDR\'];\n$bip = $_SERVER[\'HTTP_X_FORWARDED_FOR\'];\n$agent = $_SERVER[\'HTTP_USER_AGENT\'];\nsession_start();\n\n// Do this each time the user successfully logs in.\n$_SESSION[\'ident\'] = hash("sha256", $aip . $bip . $agent);\n\n// Do this every time the client makes a request to the server, after authenticating\n$ident = hash("sha256", $aip . $bip . $agent);\nif ($ident != $_SESSION[\'ident\'])\n{\n    end_session();\n    header("Location: login.php");\n    // add some fancy pants GET/POST var headers for login.php, that lets you\n    // know in the login page to notify the user of why they\'re being challenged\n    // for login again, etc.\n}\n</code></pre>\n\n<p>What this does is capture \'contextual\' information about the user\'s session, pieces of information which should not change during the life of a single session. A user isn\'t going to be at a computer in the US and in China at the same time, right? So if the IP address changes suddenly within the same session that strongly implies a session hijacking attempt, so you secure the session by ending the session and forcing the user to re-authenticate. This thwarts the hack attempt, the attacker is also forced to login instead of gaining access to the session. Notify the user of the attempt (ajax it up a bit), and vola, Slightly annoyed+informed user and their session/information is protected.</p>\n\n<p>We throw in User Agent and X-FORWARDED-FOR to do our best to capture uniqueness of a session for systems behind proxies/networks. You may be able to use more information then that, feel free to be creative.</p>\n\n<p>It\'s not 100%, but it\'s pretty damn effective.</p>\n\n<p>There\'s more you can do to protect sessions, expire them, when a user leaves a website and comes back force them to login again maybe. You can detect a user leaving and coming back by capturing a blank HTTP_REFERER (domain was typed in the URL bar), or check if the value in the HTTP_REFERER equals your domain or not (the user clicked an external/crafted link to get to your site).</p>\n\n<p>Expire sessions, don\'t let them remain valid indefinitely.</p>\n\n<p>Don\'t rely on cookies, they can be stolen, it\'s one of the vectors of attack for session hijacking.</p>\n'}, {'answer_id': 21787975, 'author': 'davej', 'author_id': 2529070, 'author_profile': 'https://Stackoverflow.com/users/2529070', 'pm_score': 1, 'selected': False, 'text': '<p>Let us consider that during the login phase the client and server can agree on a secret salt value. Thereafter the server provides a count value with each update and expects the client to respond with the hash of the (secret salt + count). The potential hijacker does not have any way to obtain this secret salt value and thus cannot generate the next hash.</p>\n'}, {'answer_id': 32047523, 'author': 'Hatch', 'author_id': 1167116, 'author_profile': 'https://Stackoverflow.com/users/1167116', 'pm_score': 2, 'selected': False, 'text': '<p>There are many ways to create protection against session hijack, however all of them are either reducing user satisfaction or are not secure.</p>\n\n<ul>\n<li><p>IP and/or X-FORWARDED-FOR checks. These work, and are pretty secure... but imagine the pain of users. They come to an office with WiFi, they get new IP address and lose the session. Got to log-in again.</p></li>\n<li><p>User Agent checks. Same as above, new version of browser is out, and you lose a session. Additionally, these are really easy to "hack". It\'s trivial for hackers to send fake UA strings.</p></li>\n<li><p>localStorage token. On log-on generate a token, store it in browser storage and store it to encrypted cookie (encrypted on server-side). This has no side-effects for user (localStorage persists through browser upgrades). It\'s not as secure - as it\'s just security through obscurity. Additionally you could add some logic (encryption/decryption) to JS to further obscure it.</p></li>\n<li><p>Cookie reissuing. This is probably the right way to do it. The trick is to only allow one client to use a cookie at a time. So, active user will have cookie re-issued every hour or less. Old cookie is invalidated if new one is issued. Hacks are still possible, but much harder to do - either hacker or valid user will get access rejected. </p></li>\n</ul>\n'}, {'answer_id': 48724010, 'author': 'Jzf', 'author_id': 2681197, 'author_profile': 'https://Stackoverflow.com/users/2681197', 'pm_score': 2, 'selected': False, 'text': '<p>AFAIK the session object is not accessible at the client, as it is stored at the web server. However, the session id is stored as a Cookie and it lets the web server track the user\'s session.</p>\n\n<p>To prevent session hijacking using the session id, you can store a hashed string inside the session object, made using a combination of two attributes, remote addr and remote port, that can be accessed at the web server inside the request object. These attributes tie the user session to the browser where the user logged in. </p>\n\n<p>If the user logs in from another browser or an incognito mode on the same system, the IP addr would remain the same, but the port will be different. Therefore, when the application is accessed, the user would be assigned a different session id by the web server.</p>\n\n<p>Below is the code I have implemented and tested by copying the session id from one session into another. It works quite well. If there is a loophole, let me know how you simulated it.</p>\n\n<pre><code>@Override\nprotected void doGet(HttpServletRequest request, HttpServletResponse response)\n        throws ServletException, IOException {\n    HttpSession session = request.getSession();\n    String sessionKey = (String) session.getAttribute("sessionkey");\n    String remoteAddr = request.getRemoteAddr();\n    int remotePort = request.getRemotePort();\n    String sha256Hex = DigestUtils.sha256Hex(remoteAddr + remotePort);\n    if (sessionKey == null || sessionKey.isEmpty()) {\n        session.setAttribute("sessionkey", sha256Hex);\n        // save mapping to memory to track which user attempted\n        Application.userSessionMap.put(sha256Hex, remoteAddr + remotePort);\n    } else if (!sha256Hex.equals(sessionKey)) {\n        session.invalidate();\n        response.getWriter().append(Application.userSessionMap.get(sessionKey));\n        response.getWriter().append(" attempted to hijack session id ").append(request.getRequestedSessionId()); \n        response.getWriter().append("of user ").append(Application.userSessionMap.get(sha256Hex));\n        return;\n    }\n    response.getWriter().append("Valid Session\\n");\n}\n</code></pre>\n\n<p>I used the SHA-2 algorithm to hash the value using the example given at <a href="http://www.baeldung.com/sha-256-hashing-java" rel="nofollow noreferrer">SHA-256 Hashing at baeldung</a></p>\n\n<p>Looking forward to your comments.</p>\n'}, {'answer_id': 66145382, 'author': 'NetDiver', 'author_id': 5194060, 'author_profile': 'https://Stackoverflow.com/users/5194060', 'pm_score': 0, 'selected': False, 'text': "<p>Use SSL only and instead of encrypting the HTTP_USER_AGENT in the session id and verifying it on every request, just store the HTTP_USER_AGENT string in your session db as well.</p>\n<p>Now you only have a simple server based string compare with the ENV'HTTP_USER_AGENT'.</p>\n<p>Or you can add a certain variation in your string compare to be more robust against browser version updates.\nAnd you could reject certain HTTP_USER_AGENT id's. (empty ones i.e.)\nDoes not resolve the problem completley, but it adds at least a bit more complexity.</p>\n<p>Another method could be using more sophisticated browser fingerprinting techniques and combine theyse values with the HTTP_USER_AGENT and send these values from time to time in a separate header values. But than you should encrypt the data in the session id itself.</p>\n<p>But that makes it far more complex and raises the CPU usage for decryption on every request.</p>\n"}, {'answer_id': 66576481, 'author': 'Danger Saints', 'author_id': 200513, 'author_profile': 'https://Stackoverflow.com/users/200513', 'pm_score': 0, 'selected': False, 'text': '<p>If ISP hijack the certificate-verification, ISP will possibly initiate a Man-in-the-middle attack. Especially with a compromised certificate authorities.</p>\n<p>So I believe you can not prevent session hijack from ISP. Especially when legal forces come with a fake certificate got from CA under law enforce.</p>\n<p>You will need something outside the network to protect your session, for example one time pad. This is why one time pad so sensitive and can only be sold by few companies.</p>\n<p>Be careful, one time pad may be exploited. Choose your one time pad with profession.</p>\n'}]
['https://Stackoverflow.com/questions/22880', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/1341/']