Even if the connection is encrypted, the session ID may still be vulnerable. If the session ID is stored in a cookie on the client, it is possible to trick the browser into sending the cookie unencrypted. This can happen if the cookie was set up by the server without the
secure parameter that prevents cookie transmission over an insecure connection. Cookie parameters and how to set up PHP session management to secure cookies are discussed in Chapter 8.
Hijack attempts can also be less sophisticated. A hacker can hijack a session by randomly trying session IDs in the hope that an existing session might be found. On a busy site many hundreds of sessions might exist at any one time, increasing the chance of the success of such an attack. One precaution is to reduce the number of idle sessions by setting short maximum lifetimes for dormant sessions, as discussed in Chapter 8.
Another precaution is to use session IDs that are hard to guess. The default PHP session management uses a random number-that can be configured with a random seed-passed through an MD5hashing algorithm, which generates a 32-character ID. The randomness and use of MD5 hashing in PHP session IDs make them much harder to guess than an ID based on other parameters, such as the system time, the client IP address, or the username.
Recording IP addresses to detect session hijack attempts
Earlier in this chapter we showed how to access the IP address of the browser when processing a request. The script shown in Example 9-5 checked the IP address set in the
$REMOTE_ADDR variable against a hardcoded value to limit access to users on a particular subnet.
The IP address of the client that sent a request can be used to help prevent session hijacking. If the IP address set in
$REMOTE_ADDR variable is recorded as a session variable when a user initially connects to an application, subsequent requests can be checked and allowed only if they are sent from the same IP address.