est.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. <?php
  2. require('config.php');
  3. $params = split("/", $_SERVER["PATH_INFO"], 3);
  4. $realm = $params[1];
  5. $cmd = $params[2];
  6. $method = $_SERVER["REQUEST_METHOD"];
  7. unset($user);
  8. unset($rowid);
  9. if (!empty($_SERVER['PHP_AUTH_DIGEST'])) {
  10. $needed = array('nonce'=>1, 'nc'=>1, 'cnonce'=>1, 'qop'=>1, 'username'=>1,
  11. 'uri'=>1, 'response'=>1);
  12. $data = array();
  13. $keys = implode('|', array_keys($needed));
  14. preg_match_all('@(' . $keys . ')=(?:([\'"])([^\2]+?)\2|([^\s,]+))@',
  15. $_SERVER['PHP_AUTH_DIGEST'], $matches, PREG_SET_ORDER);
  16. foreach ($matches as $m) {
  17. $data[$m[1]] = $m[3] ? $m[3] : $m[4];
  18. unset($needed[$m[1]]);
  19. }
  20. if ($needed) {
  21. error_log("EST: Missing auth parameter");
  22. die('Authentication failed');
  23. }
  24. $user = $data['username'];
  25. if (strlen($user) < 1) {
  26. error_log("EST: Empty username");
  27. die('Authentication failed');
  28. }
  29. $db = new PDO($osu_db);
  30. if (!$db) {
  31. error_log("EST: Could not access database");
  32. die("Could not access database");
  33. }
  34. $sql = "SELECT rowid,password,operation FROM sessions " .
  35. "WHERE user='$user' AND realm='$realm'";
  36. $q = $db->query($sql);
  37. if (!$q) {
  38. error_log("EST: Session not found for user=$user realm=$realm");
  39. die("Session not found");
  40. }
  41. $row = $q->fetch();
  42. if (!$row) {
  43. error_log("EST: Session fetch failed for user=$user realm=$realm");
  44. die('Session not found');
  45. }
  46. $rowid = $row['rowid'];
  47. $oper = $row['operation'];
  48. if ($oper != '5') {
  49. error_log("EST: Unexpected operation $oper for user=$user realm=$realm");
  50. die("Session not found");
  51. }
  52. $pw = $row['password'];
  53. if (strlen($pw) < 1) {
  54. error_log("EST: Empty password for user=$user realm=$realm");
  55. die('Authentication failed');
  56. }
  57. $A1 = md5($user . ':' . $realm . ':' . $pw);
  58. $A2 = md5($method . ':' . $data['uri']);
  59. $resp = md5($A1 . ':' . $data['nonce'] . ':' . $data['nc'] . ':' .
  60. $data['cnonce'] . ':' . $data['qop'] . ':' . $A2);
  61. if ($data['response'] != $resp) {
  62. error_log("EST: Incorrect authentication response for user=$user realm=$realm");
  63. die('Authentication failed');
  64. }
  65. }
  66. if ($method == "GET" && $cmd == "cacerts") {
  67. $fname = "$osu_root/est/$realm-cacerts.pkcs7";
  68. if (!file_exists($fname)) {
  69. error_log("EST: cacerts - unknown realm $realm");
  70. die("Unknown realm");
  71. }
  72. header("Content-Transfer-Encoding: base64");
  73. header("Content-Type: application/pkcs7-mime");
  74. $data = file_get_contents($fname);
  75. echo wordwrap(base64_encode($data), 72, "\n", true);
  76. echo "\n";
  77. error_log("EST: cacerts");
  78. } else if ($method == "GET" && $cmd == "csrattrs") {
  79. header("Content-Transfer-Encoding: base64");
  80. header("Content-Type: application/csrattrs");
  81. readfile("$osu_root/est/est-attrs.b64");
  82. error_log("EST: csrattrs");
  83. } else if ($method == "POST" && $cmd == "simpleenroll") {
  84. if (!isset($user) || strlen($user) == 0) {
  85. header('HTTP/1.1 401 Unauthorized');
  86. header('WWW-Authenticate: Digest realm="'.$realm.
  87. '",qop="auth",nonce="'.uniqid().'",opaque="'.md5($realm).'"');
  88. error_log("EST: simpleenroll - require authentication");
  89. die('Authentication required');
  90. }
  91. if (!isset($_SERVER["CONTENT_TYPE"])) {
  92. error_log("EST: simpleenroll without Content-Type");
  93. die("Missing Content-Type");
  94. }
  95. if (!stristr($_SERVER["CONTENT_TYPE"], "application/pkcs10")) {
  96. error_log("EST: simpleenroll - unexpected Content-Type: " .
  97. $_SERVER["CONTENT_TYPE"]);
  98. die("Unexpected Content-Type");
  99. }
  100. $data = file_get_contents("php://input");
  101. error_log("EST: simpleenroll - POST data from php://input: " . $data);
  102. $req = base64_decode($data);
  103. if ($req == FALSE) {
  104. error_log("EST: simpleenroll - Invalid base64-encoded PKCS#10 data");
  105. die("Invalid base64-encoded PKCS#10 data");
  106. }
  107. $cadir = "$osu_root/est";
  108. $reqfile = "$cadir/tmp/cert-req.pkcs10";
  109. $f = fopen($reqfile, "wb");
  110. fwrite($f, $req);
  111. fclose($f);
  112. $req_pem = "$reqfile.pem";
  113. if (file_exists($req_pem))
  114. unlink($req_pem);
  115. exec("openssl req -in $reqfile -inform DER -out $req_pem -outform PEM");
  116. if (!file_exists($req_pem)) {
  117. error_log("EST: simpleenroll - Failed to parse certificate request");
  118. die("Failed to parse certificate request");
  119. }
  120. /* FIX: validate request and add HS 2.0 extensions to cert */
  121. $cert_pem = "$cadir/tmp/req-signed.pem";
  122. if (file_exists($cert_pem))
  123. unlink($cert_pem);
  124. exec("openssl x509 -req -in $req_pem -CAkey $cadir/cakey.pem -out $cert_pem -CA $cadir/cacert.pem -CAserial $cadir/serial -days 365 -text");
  125. if (!file_exists($cert_pem)) {
  126. error_log("EST: simpleenroll - Failed to sign certificate");
  127. die("Failed to sign certificate");
  128. }
  129. $cert = file_get_contents($cert_pem);
  130. $handle = popen("openssl x509 -in $cert_pem -serial -noout", "r");
  131. $serial = fread($handle, 200);
  132. pclose($handle);
  133. $pattern = "/serial=(?P<snhex>[0-9a-fA-F:]*)/m";
  134. preg_match($pattern, $serial, $matches);
  135. if (!isset($matches['snhex']) || strlen($matches['snhex']) < 1) {
  136. error_log("EST: simpleenroll - Could not get serial number");
  137. die("Could not get serial number");
  138. }
  139. $sn = str_replace(":", "", strtoupper($matches['snhex']));
  140. $user = "cert-$sn";
  141. error_log("EST: user = $user");
  142. $cert_der = "$cadir/tmp/req-signed.der";
  143. if (file_exists($cert_der))
  144. unlink($cert_der);
  145. exec("openssl x509 -in $cert_pem -inform PEM -out $cert_der -outform DER");
  146. if (!file_exists($cert_der)) {
  147. error_log("EST: simpleenroll - Failed to convert certificate");
  148. die("Failed to convert certificate");
  149. }
  150. $der = file_get_contents($cert_der);
  151. $fingerprint = hash("sha256", $der);
  152. $pkcs7 = "$cadir/tmp/est-client.pkcs7";
  153. if (file_exists($pkcs7))
  154. unlink($pkcs7);
  155. exec("openssl crl2pkcs7 -nocrl -certfile $cert_pem -out $pkcs7 -outform DER");
  156. if (!file_exists($pkcs7)) {
  157. error_log("EST: simpleenroll - Failed to prepare PKCS#7 file");
  158. die("Failed to prepare PKCS#7 file");
  159. }
  160. if (!$db->exec("UPDATE sessions SET user='$user', cert='$fingerprint', cert_pem='$cert' WHERE rowid=$rowid")) {
  161. error_log("EST: simpleenroll - Failed to update session database");
  162. die("Failed to update session database");
  163. }
  164. header("Content-Transfer-Encoding: base64");
  165. header("Content-Type: application/pkcs7-mime");
  166. $data = file_get_contents($pkcs7);
  167. $resp = wordwrap(base64_encode($data), 72, "\n", true);
  168. echo $resp . "\n";
  169. error_log("EST: simpleenroll - PKCS#7 response: " . $resp);
  170. } else {
  171. header("HTTP/1.0 404 Not Found");
  172. error_log("EST: Unexpected method or path");
  173. die("Unexpected method or path");
  174. }
  175. ?>