If a session ID can be guessed (not generated with a secure pseudo random generator, or with insufficient length ...) an attacker may be able to hijack another user's session.


== Ask Yourself Whether

* the session ID is not unique.
* the session ID is set from a user-controlled input.
* the session ID is generated with not secure pseudo random generator.
* the session ID length is too short.

There is a risk if you answered yes to any of those questions.


== Recommended Secure Coding Practices

Don't manually generate session IDs, use instead language based native functionality.


== Sensitive Code Example

----
session_id(bin2hex(random_bytes(4))); // Sensitive: 4 bytes is too short
session_id($_POST["session_id"]); // Sensitive: session ID can be specified by the user
----


== Compliant Solution

[source,php]
----
session_regenerate_id(); ; // Compliant
session_id(bin2hex(random_bytes(16))); // Compliant
----


== See

* OWASP - https://owasp.org/Top10/A04_2021-Insecure_Design/[Top 10 2021 Category A4 - Insecure Design]
* OWASP - https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/[Top 10 2021 Category A7 - Identification and Authentication Failures]
* OWASP - https://owasp.org/www-project-top-ten/2017/A6_2017-Security_Misconfiguration[Top 10 2017 Category A6 - Security Misconfiguration]
* https://owasp.org/www-community/attacks/Session_fixation[OWASP Sesssion Fixation]
* CWE - https://cwe.mitre.org/data/definitions/330[CWE-330 - Use of Insufficiently Random Values]
* CWE - https://cwe.mitre.org/data/definitions/340[CWE-340 - Generation of Predictable Numbers or Identifiers]
* https://www.php.net/random-bytes[PHP: random_bytes()]
* https://www.php.net/session-regenerate-id[PHP: session_regenerate_id()] 


ifdef::env-github,rspecator-view[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Make sure the generation of the session ID is safe here.


'''
== Comments And Links
(visible only on this page)

=== on 19 Jan 2021, 09:27:32 Costin Zaharia wrote:
As far as I can tell, this rule does not apply for Asp.Net. According to documentation: "The SessionID value is randomly generated by ASP.NET and stored in a non-expiring session cookie in the browser." Source: https://docs.microsoft.com/en-us/dotnet/api/system.web.sessionstate.httpsessionstate.sessionid?view=netframework-4.8#System_Web_SessionState_HttpSessionState_SessionID[HttpSessionState.SessionID Property]


This property is read-only (does not have a setter) and the class is sealed so this behavior cannot be easily changed.


For Asp.Net Core the behavior is similar. An implementation of https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.http.isession.id?view=aspnetcore-5.0#Microsoft_AspNetCore_Http_ISession_Id[ISession] is provided by the framework and the *Id* is read-only.

endif::env-github,rspecator-view[]
