# Session Injection
If an attacker can manipulate the contents of their session cookie, they can potentially escalate the privileges they are running under. A **session injection** attacks is when a malicious user hijacks, tampers with, or spoofs a session cookie to gain unauthorized access.
## Session Hijacking
If an attacker can hijack a users’ session, they can perform actions on that users’ behalf. Session cookies can be hijacked by *cross-site scripting* (XSS) attacks if cookies are accessible from JavaScript. They can also be hijacked via *man-in-middle* attacks if cookies are sent over unencrypted HTTP requests.
To mitigate these threats, ensure the cookie is only sent over HTTPS by adding the `Secure` keyword response header, and stop client-side JavaScript to accessing the cookie by adding the `HttpOnly` keyword.
In the Flask web-server, for example, you can do this with configuration options:
“`python from flask import Flaskapp = Flask(__name__) app.config.update( |
## Session Tampering
If session state is kept in a cookie, the cookie should be accompanied by a *digital signature* that allows the server to detect whether a cookie has been tampered with. This signature should be recalculated when the cookie is returned from the client – an invalid signature indicates the cookie has been tampered with, and should be rejected. Here’s the digital signature algorithm used by Flask:
“`python def sign(self, value: _t_str_bytes) -> bytes: “””Signs the given string and also attaches time information.””” value = want_bytes(value) timestamp = base64_encode(int_to_bytes(self.get_timestamp())) sep = want_bytes(self.sep) value = value + sep + timestampreturn value + sep + self.get_signature(value) “` |
Alternatively, session state can be *encrypted* in the cookie. Unless they possess the encryption key, an attacker will not be able to read or manipulate session data.
## Session Spoofing
If your web-server generates session IDs, and those session IDs are insufficiently random, an attacker can send HTTP requests with random session IDs until they guess a valid ID. This will allow them to impersonate the user logged in under that session. If you use server-side sessions, you should use the built-in session ID generator, which is generally guaranteed to be secure.
Here’s how the `Flask-sessions` extension securely generates session IDs, for example:
“`python class SessionInterface(FlaskSessionInterface): def _generate_sid(self): return str(uuid4()) “` |