130n@calvinlai.com
  • About Calvin Lai (fkclai)
  • My Work
  • Cyber Security
    • Cyber Security Centre (CSC)
      • Why we need a CSC
      • CSC Team Structure: Roles, Functions, and Tools
        • Key Function & Role
        • Tools & Platforms
        • People
        • Outsource Strategy
      • HRMC Executive Paper
  • Detection and Response
    • Playbook: Threat Prioritization & Automated Response Strategies
      • Scenario: Detecting and Mitigating a Ransomware Attack
      • Scenario: DC Sync Attack Detected and Mitigated
      • Scenario: Pass-the-Hash (PtH) Attack Detected and Contained
      • Scenario: Phishing Campaign with Malware / Credential Theft Detected and Mitigated
  • Application Architecture
    • Comparison of MVC , N-tier and Microservice Architecture
  • Application Security
    • OAuth, SAML, and OpenID Connect: Key Differences and Use Cases
    • Secure Coding Principles
    • HTTP Header Security Principles
    • Mitigating Broken Object Level Authorization (BOLA)
    • Spring Boot Validation
    • Output Encoding in JavaServer Faces (JSF)
    • Session Management Security Issues
    • Common API Security Problems
      • Broken Authentication
      • Excessive Data Exposure
      • Lack of Resources & Rate Limiting
      • Broken Function Level Authorization
      • Unsafe Consumption of APIs
    • JAVA Exception Handling
    • File Upload Validation
    • OAuth 2.0 Security
      • Insecure Storage of Access Tokens
    • Microservice Security
      • Sample Coding Demo
        • Service Implementation
        • Client Interaction
      • Security Solution for Microservices Architecture
    • Modifying and Protecting Java Class Files
      • Modify a Class File Inside a WAR File
      • Direct Bytecode Editing
        • Steps to Directly Edit a Java Class File
          • Update: Java Bytecode Editing Tools
      • Techniques to Protect Java Class Files
        • Runtime Decryption in WebLogic
    • JAVA Program
      • Secure, Concurrent Web Access Using Java and Tor
      • Creating a Maven Java project in Visual Studio Code
  • Exploit/CVE PoC
    • ZeroLogon Exploit
    • Remote Retrieved Chrome saved Encrypted Password
    • Twitter Control an RCE attack
  • Hacking Report (HTB)
    • Hits & Summary
      • Tools & Cheat Sheet
    • Windows Machine
      • Love 10.10.10.239
      • Blackfield 10.10.10.192
      • Remote 10.10.10.180
      • Sauna 10.10.10.175
      • Forest 10.10.10.161
      • Sniper
      • Json
      • Heist
      • Blue
      • Legacy
      • Resolute
      • Cascade
    • Linux Machine
      • Photobomb 10.10.11.182
      • Pandora 10.10.11.136
      • BountyHunter 10.10.11.100
      • CAP 10.10.10.245
      • Spectra 10.10.10.229
      • Ready 10.10.10.220
      • Doctor 10.10.10.209
      • Bucket 10.10.10.212
      • Blunder 10.10.10.191
      • Registry 10.10.10.159
      • Magic
      • Tabby
  • Penetration Testing
    • Web Application PenTest
    • Network/System PenTest
    • Mobile Penetration Test
      • Certificate Pinning
        • Certificate Pinning Bypass (Android)
          • Root a Android Device
          • Setup Proxy Tool - Burp Suite
      • Checklist
  • Threat Intelligence
    • Advanced Persistent Threat (APT) groups
      • North Korean APT Groups
      • Chinese APT Groups
      • Russian APT Groups
      • Other APT
  • Red Team (Windows)
    • 01 Reconnaissance
    • 02 Privileges Escalation
    • 03 Lateral Movement
    • 04 AD Attacks
      • DCSync
    • 05 Bypass-Evasion
    • 06 Kerberos Attack
    • 99 Basic Command
  • Exploitation Guide
    • 01 Reconnaissance
    • 02 Port Enumeration
    • 03 Web Enumeration
    • 04 Windows Enum & Exploit
      • Windows Credential Dumping
        • Credential Dumping: SAM
        • Credential Dumping: DCSync
      • Kerberos Attack
      • RDP
    • 05 File Enumeration
    • 06 Reverse Shell Cheat Sheet
      • Windows Reverse Shell
      • Linux Reverse Shell
    • 07 SQL Injection
    • 08 BruteForce
    • 09 XSS Bypass Checklist
    • 10 Spring Boot
    • 11 WPA
    • 12 Payload list
  • Vuln Hub (Writeup)
    • MrRobot
    • CYBERRY
    • MATRIX 1
    • Node-1
    • DPwwn-1
    • DC7
    • AiWeb-2
    • AiWeb-1
    • BrainPan
  • CTF (Writeup & Tips)
    • CTF Tools & Tips
    • Hacker One
    • CTF Learn
    • P.W.N. University - CTF 2018
    • HITCON
    • Pwnable
      • 01 Start
  • Useful Command/Tools
    • Kali
    • Windows
    • Linux
  • Offensive Security Lab & Exam
    • Lab
    • Tools for an Offensive Certification
      • Strategy for an Offensive Exam Certification
        • CVEs
        • Privilege Escalation
        • Commands
        • Impacket
  • ISO 27001
    • Disclaimer
    • What is ISO 27001
      • Implementation
    • Documentation
    • Common Mistake
    • Q&A
      • Can internal audit to replace the risk assessment
      • Is it sufficient for only the IT department head to support the ISO 27001 program
      • Does the Business Continuity Plan (BCP) and a Disaster Recovery Plan (DRP) are the same?
    • ISO 27001 Controls and Domains
      • 1. Information Security Policies
      • 2. Organization of Information Security
      • 3. Human Resource Security
      • 4. Asset Management
      • 5. Access Control
      • 6. Cryptographic Controls
      • 7. Physical and Environmental Security
      • 8: Operational Security
      • 9. Communications Security
      • 10. System Acquisition, Development, and Maintenance
      • 11. Supplier Relationships
      • 12: Information Security Incident Management
      • 13. Information Security Aspects of Business Continuity Management
      • 14. Compliance
Powered by GitBook
On this page
  • What is the Common Problem on Session Management?
  • What is the Security Issue Impact to the System?
  • Maps to OWASP Top 10
  • Vulnerable Code and Secure Code Example
  • Attack Scenario
  • Insecure Implementation (Prone to Session Fixation)
  • Secure Implementation (Mitigating Session Fixation and LDAP Authentication)
  • Key Points for Developers
  • Summary and Key Takeaways
  • Reference Links

Was this helpful?

  1. Application Security

Session Management Security Issues

What is the Common Problem on Session Management?

Common problems in session management include:

  • Session Fixation: When an attacker sets a known session ID for a user, then tricks the user into authenticating with it, allowing the attacker to hijack the session.

  • Session Hijacking: When an attacker intercepts and steals a user's session ID to gain unauthorized access.

  • Session Timeout Issues: When sessions either expire too early or remain active for too long, leading to unauthorized access or user frustration.

  • Insecure Storage: When sensitive session data is not properly stored, leading to potential data breaches and unauthorized access.

These issues can compromise the security and integrity of user sessions, leading to unauthorized access, data breaches, and other security risks.

What is the Security Issue Impact to the System?

The impact of session management security issues can be significant, including:

  • Unauthorized Access: Attackers can gain unauthorized access to user accounts and sensitive data.

  • Data Breaches: Compromised sessions can lead to data breaches, exposing sensitive information to malicious actors.

  • Denial of Service: Improper session handling can result in denial of service attacks, disrupting the availability of services.

  • User Frustration: Poor session management can lead to user frustration due to frequent session timeouts or unexpected logouts.

Maps to OWASP Top 10

Session management issues are primarily mapped to the OWASP Top 10 under "A07:2021 - Identification and Authentication Failures". This category includes vulnerabilities related to authentication and session management, such as:

  • Session Fixation: Reuse of session identifiers after successful login.

  • Improper Session Handling: Not correctly invalidating session IDs during logout or periods of inactivity.

  • Exposure of Session Identifiers: Exposing session identifiers in the URL.

These issues can lead to unauthorized access and other security risks.

Vulnerable Code and Secure Code Example

Attack Scenario

Imagine a web application that manages user sessions. An attacker could exploit weak session management practices to hijack a user's session and gain unauthorized access to their account.

This demo is focused on fixing the Session Fixation problem.

Insecure Implementation (Prone to Session Fixation)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/api")
public class SessionController {

    @PostMapping("/login")
    public ResponseEntity<?> login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
        // Authenticate user (simplified for example)
        if (authenticate(username, password)) {
            HttpSession session = request.getSession();
            session.setAttribute("user", username);
            // No session ID regeneration
            return ResponseEntity.ok("User logged in");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
    }

    private boolean authenticate(String username, String password) {
        // Simplified authentication logic
        return "user".equals(username) && "password".equals(password);
    }
}

Attack Payload Example

curl -X POST -d "username=user&password=password" http://localhost:8080/api/login

In this case, the session ID is not regenerated after login, making it vulnerable to session fixation attacks.

Secure Implementation (Mitigating Session Fixation and LDAP Authentication)

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api")
public class SessionController {

    private LdapAuthenticator ldapAuthenticator;

    public SessionController() {
        // Initialize the LDAP authenticator with LDAP URL and base DN
        this.ldapAuthenticator = new LdapAuthenticator("ldap://weblogic-server:7001", "ou=users,dc=example,dc=com");
    }

    @PostMapping("/login")
    public ResponseEntity<?> login(HttpServletRequest request, @RequestParam String username, @RequestParam String password) {
        if (ldapAuthenticator.authenticate(username, password)) {
            HttpSession session = request.getSession(false);
            if (session != null) {
                session.invalidate();
            }
            session = request.getSession(true);
            session.setAttribute("user", username);
            // **Session ID is regenerated after login**
            return ResponseEntity.ok("User logged in");
        } else {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid credentials");
        }
    }
}

LDAP Authentication Class

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;

import java.util.Hashtable;

public class LdapAuthenticator {

    private String ldapUrl;
    private String baseDn;

    public LdapAuthenticator(String ldapUrl, String baseDn) {
        this.ldapUrl = ldapUrl;
        this.baseDn = baseDn;
    }

    public boolean authenticate(String username, String password) {
        Hashtable<String, String> env = new Hashtable<>();
        env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        env.put(Context.PROVIDER_URL, ldapUrl);
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, "cn=" + username + "," + baseDn);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            DirContext ctx = new InitialDirContext(env);
            String searchFilter = "(uid=" + username + ")";
            SearchControls controls = new SearchControls();
            controls.setSearchScope(SearchControls.SUBTREE_SCOPE);

            NamingEnumeration<SearchResult> results = ctx.search(baseDn, searchFilter, controls);

            if (results.hasMore()) {
                // User found and authenticated
                ctx.close();
                return true;
            } else {
                // User not found or authentication failed
                ctx.close();
                return false;
            }
        } catch (NamingException e) {
            // Log the exception and return false for authentication failure
            e.printStackTrace();
            return false;
        }
    }
}

The secure implementation:

  • LDAP Authentication: The LdapAuthenticator class performs the authentication using JNDI to connect to the LDAP server.

    • It sets up the LDAP context with the user's credentials.

    • Searches the LDAP directory to verify the user's existence and credentials.

    • Returns true if the user is authenticated successfully, otherwise false.

  • Session Fixation Mitigation:

    • Invalidates the old session and creates a new session after successful LDAP authentication.

    • Session ID is regenerated after login, which is a key improvement to prevent session fixation attacks.

Key Points for Developers

  • Regenerate Session IDs: Ensure session IDs are regenerated after user login to prevent session fixation.

  • Use HTTPS: Encrypt data in transit to protect against session hijacking.

  • Enforce Session Timeout: Configure session timeout settings to automatically expire sessions after a period of inactivity.

  • Hard Timeout and Soft Timeout: Implement both hard timeout (session expires after a fixed duration) and soft timeout (session expires after inactivity).

  • Implement Secure Storage: Use strong encryption for data stored in sessions and follow best practices for data protection.

  • Monitor and Audit Sessions: Regularly monitor and audit sessions to detect any suspicious activity.

Summary and Key Takeaways

Session management is a critical aspect of web application security. By addressing issues like session fixation, session hijacking, session timeout, and insecure storage, developers can enhance the security of their systems and protect user data from unauthorized access and breaches.

Reference Links

PreviousOutput Encoding in JavaServer Faces (JSF)NextCommon API Security Problems

Last updated 6 months ago

Was this helpful?

OWASP Session Management Cheat Sheet
OWASP API Security Top 10
OWASP Access Control Cheat Sheet
Spring Security Documentation