login.inc.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. // This fill will perform HTTP digest authentication. This is not the most secure form of authentication so be carefull when using this.
  3. $realm = 'phpRedisAdmin';
  4. // Using the md5 of the user agent and IP should make it a bit harder to intercept and reuse the responses.
  5. $opaque = md5('phpRedisAdmin'.$_SERVER['HTTP_USER_AGENT'].$_SERVER['REMOTE_ADDR']);
  6. if (!isset($_SERVER['PHP_AUTH_DIGEST']) || empty($_SERVER['PHP_AUTH_DIGEST'])) {
  7. header('HTTP/1.1 401 Unauthorized');
  8. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.$opaque.'"');
  9. die;
  10. }
  11. $needed_parts = array(
  12. 'nonce' => 1,
  13. 'nc' => 1,
  14. 'cnonce' => 1,
  15. 'qop' => 1,
  16. 'username' => 1,
  17. 'uri' => 1,
  18. 'response' => 1
  19. );
  20. $data = array();
  21. $keys = implode('|', array_keys($needed_parts));
  22. preg_match_all('/('.$keys.')=(?:([\'"])([^\2]+?)\2|([^\s,]+))/', $_SERVER['PHP_AUTH_DIGEST'], $matches, PREG_SET_ORDER);
  23. foreach ($matches as $m) {
  24. $data[$m[1]] = $m[3] ? $m[3] : $m[4];
  25. unset($needed_parts[$m[1]]);
  26. }
  27. if (!empty($needed_parts)) {
  28. header('HTTP/1.1 401 Unauthorized');
  29. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.$opaque.'"');
  30. die;
  31. }
  32. if (!isset($config['login'][$data['username']])) {
  33. header('HTTP/1.1 401 Unauthorized');
  34. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.$opaque.'"');
  35. die('Invalid username and/or password combination.');
  36. }
  37. $login = $config['login'][$data['username']];
  38. $login['name'] = $data['username'];
  39. $password = md5($login['name'].':'.$realm.':'.$login['password']);
  40. $response = md5($password.':'.$data['nonce'].':'.$data['nc'].':'.$data['cnonce'].':'.$data['qop'].':'.md5($_SERVER['REQUEST_METHOD'].':'.$data['uri']));
  41. if ($data['response'] != $response) {
  42. header('HTTP/1.1 401 Unauthorized');
  43. header('WWW-Authenticate: Digest realm="'.$realm.'",qop="auth",nonce="'.uniqid().'",opaque="'.$opaque.'"');
  44. die('Invalid username and/or password combination.');
  45. }
  46. ?>