http-auth.php 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. $realm = 'The batcave';
  3. // Just a random id
  4. $nonce = uniqid();
  5. // Get the digest from the http header
  6. $digest = getDigest();
  7. // If there was no digest, show login
  8. if (is_null($digest)) requireLogin($realm,$nonce);
  9. $digestParts = digestParse($digest);
  10. $validUser = 'admin';
  11. $validPass = 'admin';
  12. // Based on all the info we gathered we can figure out what the response should be
  13. $A1 = md5("{$digestParts['username']}:{$realm}:{$validPass}");
  14. $A2 = md5("{$_SERVER['REQUEST_METHOD']}:{$digestParts['uri']}");
  15. $validResponse = md5("{$A1}:{$digestParts['nonce']}:{$digestParts['nc']}:{$digestParts['cnonce']}:{$digestParts['qop']}:{$A2}");
  16. if ($digestParts['response']!=$validResponse)
  17. requireLogin($realm,$nonce);
  18. else {
  19. // We're in!
  20. echo 'a7532ae474e5e66a0c16eddab02e02a7';
  21. die();
  22. }
  23. // This function returns the digest string
  24. function getDigest() {
  25. // mod_php
  26. if (isset($_SERVER['PHP_AUTH_DIGEST'])) {
  27. $digest = $_SERVER['PHP_AUTH_DIGEST'];
  28. // most other servers
  29. }
  30. elseif (isset($_SERVER['HTTP_AUTHENTICATION'])) {
  31. if (strpos(strtolower($_SERVER['HTTP_AUTHENTICATION']),'digest')===0)
  32. $digest = substr($_SERVER['HTTP_AUTHORIZATION'], 7);
  33. }
  34. elseif (isset($_SERVER['HTTP_WWW_AUTHENTICATE'])) {
  35. $digest = $_SERVER['HTTP_WWW_AUTHENTICATE'];
  36. }
  37. return $digest;
  38. }
  39. // This function forces a login prompt
  40. function requireLogin($realm,$nonce) {
  41. header('WWW-Authenticate: Digest realm="' . $realm . '",qop="auth",nonce="' . $nonce . '",opaque="' . md5($realm) . '"');
  42. header('HTTP/1.1 401');
  43. echo 'Authentication Canceled';
  44. die();
  45. }
  46. // This function extracts the separate values from the digest string
  47. function digestParse($digest) {
  48. // protect against missing data
  49. $needed_parts = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1, 'uri'=>1, 'response'=>1);
  50. $data = array();
  51. preg_match_all('@(\w+)=(?:(?:")([^"]+)"|([^\s,$]+))@', $digest, $matches, PREG_SET_ORDER);
  52. foreach ($matches as $m) {
  53. $data[$m[1]] = $m[2] ? $m[2] : $m[3];
  54. unset($needed_parts[$m[1]]);
  55. }
  56. return $needed_parts ? false : $data;
  57. }
  58. ?>