sessions.php
changeset 74 7719085707d8
parent 44 92dd253f501c
--- 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');
+}
+
 ?>