From 6eb3cdf688d885a7c9f299d8e5cdeaf8a2559ff7 Mon Sep 17 00:00:00 2001
From: Andreas Gohr <andi@splitbrain.org>
Date: Tue, 28 Feb 2017 19:12:36 +0100
Subject: [PATCH] do not use invalid session IDs #1883

When an invalid session ID is passed to PHP a warning is thrown, but the
session is still initialized with this invalid ID (throwing additional
warnings on save).

This makes sure such invalid IDs are removed from the cookie array
before initializing the session.

PHP bug references:

https://bugs.php.net/bug.php?id=68063
https://bugs.php.net/bug.php?id=73860
---
 inc/init.php | 26 +++++++++++++++++++++++---
 1 file changed, 23 insertions(+), 3 deletions(-)

diff --git a/inc/init.php b/inc/init.php
index b2319fe95..3ea7df210 100644
--- a/inc/init.php
+++ b/inc/init.php
@@ -149,9 +149,8 @@ if(!headers_sent() && !defined('NOSESSION')) {
     }
     if(!defined('DOKU_SESSION_DOMAIN'))   define ('DOKU_SESSION_DOMAIN', '');
 
-    session_name(DOKU_SESSION_NAME);
-    session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true);
-    session_start();
+    // start the session
+    init_session();
 
     // load left over messages
     if(isset($_SESSION[DOKU_COOKIE]['msg'])) {
@@ -227,6 +226,27 @@ if (!defined('NOSESSION')) {
 // setup mail system
 mail_setup();
 
+/**
+ * Initializes the session
+ *
+ * Makes sure the passed session cookie is valid, invalid ones are ignored an a new session ID is issued
+ *
+ * @link http://stackoverflow.com/a/33024310/172068
+ */
+function init_session() {
+    global $conf;
+    session_name(DOKU_SESSION_NAME);
+    session_set_cookie_params(DOKU_SESSION_LIFETIME, DOKU_SESSION_PATH, DOKU_SESSION_DOMAIN, ($conf['securecookie'] && is_ssl()), true);
+
+    // make sure the session cookie contains a valid session ID
+    if(isset($_COOKIE[DOKU_SESSION_NAME]) && !preg_match('/^[-,a-zA-Z0-9]{1,128}$/', $_COOKIE[DOKU_SESSION_NAME])) {
+        unset($_COOKIE[DOKU_SESSION_NAME]);
+    }
+
+    session_start();
+}
+
+
 /**
  * Checks paths from config file
  */
-- 
GitLab