11.2.1. ProblemYou want make sure an attacker can't access another user's session. 11.2.2. SolutionAllow passing of session IDs via cookies only, and generate an additional session token that is passed via URLs. Only requests that contain a valid session ID and a valid session token may access the session: <?php ini_set('session.use_only_cookies', true); session_start(); $salt = 'YourSpecialValueHere'; $tokenstr = (str) date('W') . $salt; $token = md5($tokenstr); if (!isset($_REQUEST['token']) || $_REQUEST['token'] != $token) { // prompt for login exit; } $_SESSION['token'] = $token; output_add_rewrite_var('token', $token); ?> If you're using a PHP version earlier than 4.3.0, output_add_rewrite_var( ) is not available. Instead, use the code in Example 11-1. Adding a session token to links
The regular expression for matching hyperlinks in the inject_session_token( ) function isn't bulletproof; it will not catch hyperlinks with href attributes quoted with single quotes. 11.2.3. DiscussionThis example creates an auto-shifting token by joining the current week number together with a salt term of your choice. With this technique, tokens will be valid for a reasonable period of time without being fixed. We then check for the token in the request, and if it's not found, we prompt for a new login. If it is found, it needs to be added to generated links. output_add_rewrite_var( ) does this easily. Without output_add_rewrite_var( ), we continue generating the page and declare an output buffer callback function that will make sure that any hyperlinks on the page are modified to contain the current token before the page is displayed. Note that the inject_session_token( ) function in the example does not address imagemaps, form submissions, or Ajax calls; make sure that you adjust any such functionality on a page to include the session token that's been generated and stored in the session. 11.2.4. See AlsoRecipe 18.1 for more information on regenerating IDs to prevent session fixation. |