Security: Sessions are now based on HMAC-MD5 salts instead of concatenation
authorDan
Fri, 12 Jun 2009 11:57:08 -0400
changeset 74 7719085707d8
parent 73 1f55c324efcf
child 75 2f39cb7f54c4
Security: Sessions are now based on HMAC-MD5 salts instead of concatenation
functions.php
sessions.php
--- a/functions.php	Fri Jun 12 11:38:43 2009 -0400
+++ b/functions.php	Fri Jun 12 11:57:08 2009 -0400
@@ -333,3 +333,21 @@
   }
 }
 
+/**
+ * Decodes a hex string.
+ * @param string $hex The hex code to decode
+ * @return string
+ */
+
+function hexdecode($hex)
+{
+  $hex = str_split($hex, 2);
+  $bin_key = '';
+  foreach($hex as $nibble)
+  {
+    $byte = chr(hexdec($nibble));
+    $bin_key .= $byte;
+  }
+  return $bin_key;
+}
+
--- a/sessions.php	Fri Jun 12 11:38:43 2009 -0400
+++ b/sessions.php	Fri Jun 12 11:57:08 2009 -0400
@@ -72,6 +72,10 @@
 function session_check()
 {
   global $use_auth, $auth_data;
+  
+  if ( !$use_auth )
+    return true;
+  
   if ( isset($_COOKIE['grey_session']) )
   {
     load_session_data();
@@ -82,10 +86,11 @@
       $session =& $session_data[$_COOKIE['grey_session']];
       if ( isset($auth_data[$session['user']]) )
       {
-        if ( $session['hash'] === md5($auth_data[$session['user']] . $session['salt']) )
+        $password =& $auth_data[$session['user']];
+        if ( $session['hash'] === hmac_md5($password, $session['salt']) )
         {
           // session is valid, logged in
-          return true;
+          return $session['user'];
         }
       }
     }
@@ -119,7 +124,7 @@
   
   $session_data[$sessid] = array(
       'user' => $username,
-      'hash' => md5($password . $salt),
+      'hash' => hmac_md5($password, $salt),
       'salt' => $salt
     );
   session_commit_db();
@@ -174,4 +179,63 @@
 
 $session_data = array();
 
+/*
+ * All this HMAC stuff is ported (ok, copied and pasted) from Enano.
+ * Hey, I own the copyright on it.
+ */
+
+function hmac_core($message, $key, $hashfunc)
+{
+  if ( strlen($key) % 2 == 1 )
+    $key .= '0';
+  
+  if ( strlen($key) > 128 )
+    $key = $hashfunc($key);
+  
+  while ( strlen($key) < 128 )
+  {
+    $key .= '00';
+  }
+  $opad = hmac_hexbytearray($key);
+  $ipad = $opad;
+  for ( $i = 0; $i < count($ipad); $i++ )
+  {
+    $opad[$i] = $opad[$i] ^ 0x5c;
+    $ipad[$i] = $ipad[$i] ^ 0x36;
+  }
+  $opad = hmac_bytearraytostring($opad);
+  $ipad = hmac_bytearraytostring($ipad);
+  return $hashfunc($opad . hexdecode($hashfunc($ipad . $message)));
+}
+
+function hmac_hexbytearray($val)
+{
+  $val = hexdecode($val);
+  return hmac_bytearray($val);
+}
+
+function hmac_bytearray($val)
+{
+  $val = str_split($val, 1);
+  foreach ( $val as &$char )
+  {
+    $char = ord($char);
+  }
+  return $val;
+}
+
+function hmac_bytearraytostring($val)
+{
+  foreach ( $val as &$char )
+  {
+    $char = chr($char);
+  }
+  return implode('', $val);
+}
+
+function hmac_md5($message, $key)
+{
+  return hmac_core($message, $key, 'md5');
+}
+
 ?>