Session Management Basics

Session Security

The session module can not guarantee that the information stored in a session is only viewed by the user who created the session. Additional measures are needed to protect the confidentiality of the session, depending on the value associated with it.

The importance of the data carried in the session needs to be assessed and further protection may be deployed; this typically comes at a price, such as reduced convenience for the user. For example, to protect users from a simple social engineering tactic, session.use_only_cookies needs to be enabled. In that case, cookies must be enabled unconditionally on the client side, or sessions will not work.

There are several ways to leak an existing session ID to third parties. E.g. JavaScript injections, session IDs in URLs, packet sniffing, physical access to the device, etc. A leaked session ID enables the third party to access all resources associated with a specific ID. First, URLs carrying session IDs. If there are links to an external site or resource, the URL including the session ID might be stored in the external site's referrer logs. Second, a more active attacker might listen to network traffic. If it is unencrypted, session IDs will flow in plain text over the network. The solution is to implement SSL/TLS on the server and make it mandatory for users. HSTS should be used for improved security.

Notă: Even HTTPS can not protect confidential data at all times. For example the CRIME and Beast vulnerabilities may enable an attacker to read the data. Also, note that many networks employ HTTPS MITM proxies for audit purposes. Attackers may also set up such a proxy.

Nonadaptive Session Management

PHP's session manager is adaptive by default currently. An adaptive session manager bears additional risks.

As of PHP 5.5.2, session.use_strict_mode is available. When it is enabled, and the session save handler supports it, an uninitialized session ID is rejected and a new one is created. This prevents an attack that forces users to use a known session ID. An attacker may paste links or send emails that contains the session ID. E.g. http://example.com/page.php?PHPSESSID=123456789 if session.use_trans_sid is enabled, the victim will start a session using the session ID provided by the attacker. session.use_strict_mode mitigate this risk.

Avertizare

User defined save handlers can also support strict session mode by implementing session ID validation. All user defined save handlers should implement session ID validation.

The session ID cookie may be set with the domain, path, httponly, secure and, as of PHP 7.3, SameSite attributes. There is precedence defined by browsers. By using the precedence, an attacker can set session ID that could be used permanently. Use of session.use_only_cookies will not solve this issue. session.use_strict_mode mitigates this risk. With session.use_strict_mode=On, the uninitialized session ID will be refused.

Notă: Even though session.use_strict_mode mitigates the risk of adaptive session management, an attacker can force users to use an initialized session ID which has been created by an attacker. E.g. JavaScript injection. This attack can be mitigated by this manual's recommendations. By following this manual, developers should enable, session.use_strict_mode, use timestamp based session management, and regenerate session IDs using session_regenerate_id() with recommended procedures. If developers follow all of the above, an attacker generated session ID will eventually be deleted. When an access to an obsolete session occurs, developers should save all active session data of the user. As this information will be relevant for an ensuing investigation. The user should be forcefully logged out of all sessions, i.e. require them to reauthenticate. This prevents attackers from abusing stolen sessions.

Avertizare

Access to an obsolete session does not necessarily suggest an attack. An unstable network and/or immediate deletion of the active session will result in legitimate users using obsolete sessions.

As of PHP 7.1.0, session_create_id() has been added. This function may be operated to access all active sessions of a user efficiently by prefixing the session IDs with the user ID. Enabling session.use_strict_mode is vital with this setup. Otherwise, malicious users can set malicious session ID for other users.

Notă: Users prior to PHP 7.1.0 SHOULD use CSPRNG, e.g. /dev/urandom, or random_bytes() and hash functions to generate a new session ID. session_create_id() has collision detection and generates a session ID according to the session's INI settings. Use of session_create_id() is preferred.

Session ID Regeneration

session.use_strict_mode is a good mitigation, however not sufficient. Developers must equally use session_regenerate_id() for session security.

Session ID regeneration reduces the risk of stolen session IDs, thus session_regenerate_id() must be called periodically. E.g. Regenerate the session ID every 15 minutes for security sensitive content. Even in the case that a session ID is stolen, both the legitimate user's and the attacker's session will expire. In other words access by the user or the attacker will generate an obsolete session access error.

Session IDs must be regenerated when user privileges are elevated, such as after authenticating. session_regenerate_id() must be called prior to setting the authentication information to $_SESSION. (As of PHP 7.0.0, session_regenerate_id() saves the current session data automatically in order to save timestamp/etc. to the current session.) Ensure only the new session contains the authenticated flag.

Developers must not rely on session ID expiration by session.gc_maxlifetime. Attackers may access a victim's session ID periodically to prevent its expiration and keep exploiting it, including an authenticated session.

Instead, developers must implement timestamp based session data management.

Avertizare

Although the session manager can manage timestamps transparently, this feature is not implemented. Old session data must be kept until GC. Simultaneously, developers must assure themselves obsolete session data is removed. However, developers must not remove active session data immediately. I.e. session_regenerate_id(true); and session_destroy() must never be called together for an active session. This may sound contradictory, but this is a mandatory requirement.

session_regenerate_id() does not delete outdated sessions by default. Obsolete authenticated sessions may be present for use. Developers must prevent outdated sessions to be consumed by anyone. They must prohibit access to obsolete session data by themselves using timestamps.

Avertizare

The sudden removal of an active session produces undesirable side effects. Sessions can vanish when there are concurrent connections to the web application and/or the network is unstable.

Potential malicious access is undetectable with the sudden removal of active sessions.

Instead of deleting outdated sessions immediately, developers must set a short-term expiration time (timestamp) in $_SESSION, and prohibit access to the session data by themselves.

Developers must not prohibit access to old session data immediately after session_regenerate_id(). It must be prohibited at a later stage. E.g. a few seconds later for stable networks, like a wired network, and a few minutes later for unstable networks such as cell phones or Wi-Fi.

If a user accesses an obsolete session (expired session), access to it should be denied. It is also recommended to remove the authenticated status from all of the user's sessions to as it is likely to represent an attack.

Proper use of session.use_only_cookies and session_regenerate_id() can cause personal DoS with undeletable cookies set by attackers. In this case, developers may invite users to remove cookies and advise them they may be affected by a security issue. Attackers may set malicious cookies via a vulnerable web application, an exposed/vicious browser plugin, a physically compromised device, etc.

Avertizare

Do not misunderstand the DoS risk. use_strict_mode=On is mandatory for general session ID security! All sites are advised to enable use_strict_mode.

DoS can only happen when the account is under attack. A JavaScript injection vulnerability in an application represents the most common cause.

Session Data Deletion

Obsolete session data must be inaccessible and deleted. The current session module does not handle this well.

Obsolete session data should be removed as soon as possible. However, active sessions must not be removed instantly. To satisfy those requirements, developers must implement timestamp based session data management by themselves.

Set and manage expiration timestamp in $_SESSION. Prohibit access to outdated session data. When access to obsolete session data is detected, it is advised to remove all authenticated status from the user's sessions and force them to re-authenticate. Access to obsolete session data can represent an attack. To achieve this, developers must keep track of all active sessions of every user.

Notă: Access to an obsolete session can also happen because of an unstable network and/or concurrent access to the web site. E.g the server tried to set a new session ID via a cookie, but the Set-Cookie packet may not have reached the client due to loss of connection. One connection may issue a new session ID by session_regenerate_id(), but another concurrent connection may not have received the new session ID yet. Therefore, developers must prohibit access to obsolete session at a later stage. I.e. timestamp based session management is mandatory.

In summary, session data must not be destroyed with session_regenerate_id() nor session_destroy(), but timestamps must be used to control access to session data. Let session_gc() remove obsolete data from the session data storage.

Session and Locking

Session data is locked to avoid race conditions by default. Locking is mandatory to keep session data consistent across requests.

However, session-locking can be abused by attackers to perform DoS attacks. To mitigate the risk of a DoS attack by session-locking, minimize locks. Use read only sessions when session data does not need to be updated. Use the 'read_and_close' option with session_start(). session_start(['read_and_close'=>1]); Close the session as soon as possible after updating $_SESSION by using session_commit().

The current session module does not detect any modification of $_SESSION when the session is inactive. It is the developer's responsibility not to modify $_SESSION when the session is inactive.

Active Sessions

Developers should keep track of all active sessions for every user. And notify them of how many active sessions, from which IP (and area), how long it has been active, etc. PHP does not keep track of these. Developers are supposed to do so.

Various ways to implement this exist. One possible implementation is setting up a database that keeps track of the required data and stores any relevant information. Since session data is GCed, developers must take care of the GCed data to maintain the active session database consistency.

One of the simplest implementations is "User ID prefixed session ID" and store the required information in $_SESSION. Many databases posses good performance for selecting string prefix. Developers MAY use session_regenerate_id() and session_create_id() for this.

Avertizare

Never employ confidential data as a prefix. If the user ID is confidential, consider using hash_hmac().

Avertizare

Enabling session.use_strict_mode is mandatory for this setup. Ensure it is enabled. Otherwise the active session database can be compromised.

Timestamp based session management is mandatory to detect access to obsolete sessions. When access to an obsolete session is detected, authentication flags should be removed from all active sessions of the user. This prevents attackers to keep exploiting stolen sessions.

Session and Auto-login

Developers must not use long life session IDs for auto-login because it increases the risk of stolen sessions. An auto-login feature should be implemented by the developer.

Use a secure one time hash key as an auto-login key using setcookie(). Use a secure hash stronger than SHA-2. E.g. SHA-256 or greater with random data from random_bytes() or /dev/urandom.

If the user is unauthenticated, check whether the one-time auto-login key is valid or not. In the case it is valid, authenticate the user and set a new secure one-time hash key. An auto-login key must only be used once, i.e. never reuse an auto-login key, always generate a new one.

An auto-login key is a long life authentication key, it should be protected as much as possible. Use path/httponly/secure/SameSite cookie attributes to secure it. I.e. never transmit the auto-login key unless required.

Developer must implement the features that disables auto-login and removes unneeded auto-login key cookie.

CSRF (Cross-Site Request Forgeries) attacks

Sessions and authentication do not protect against CSRF attacks. Developers must implement CSRF protection by themselves.

output_add_rewrite_var() can be used for CSRF protection. Refer to the manual page for more details.

Notă: PHP prior to 7.2.0 uses the same output buffer and INI setting as trans sid. Therefore, use of output_add_rewrite_var() with PHP prior to version 7.2.0 is not advised.

Most web application frameworks support CSRF protection. Refer to the web application framework manual for more details.

As of PHP 7.3 the SameSite attribute for the session cookie can be set. This is an additional measure which can mitigate CSRF vulnerabilities.