*/}}

index.php 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. <?php
  2. function error_page($header, $body, $http = '400 Bad Request')
  3. {
  4. $protocol = isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0';
  5. header($protocol . ' ' . $http);
  6. $html = <<<HTML
  7. <!doctype html>
  8. <html>
  9. <head>
  10. <style>
  11. .error{
  12. width:100%;
  13. text-align:center;
  14. margin-top:10%;
  15. }
  16. </style>
  17. <title>Error: $header</title>
  18. </head>
  19. <body>
  20. <div class='error'>
  21. <h1>Error: $header</h1>
  22. <p>$body</p>
  23. </div>
  24. </body>
  25. </html>
  26. HTML;
  27. die($html);
  28. }
  29. $configfile= __DIR__ . '/config.php';
  30. if (file_exists($configfile)) {
  31. include_once $configfile;
  32. } else {
  33. error_page(
  34. 'Configuration Error',
  35. 'Endpoint not yet configured, visit <a href="setup.php">setup.php</a> for instructions on how to set it up.'
  36. );
  37. }
  38. // Enable string comparison in constant time.
  39. if (!function_exists('hash_equals')) {
  40. function hash_equals($known_string, $user_string)
  41. {
  42. $known_length = strlen($known_string);
  43. if ($known_length !== strlen($user_string)) {
  44. return false;
  45. }
  46. $match = 0;
  47. for ($i = 0; $i < $known_length; $i++) {
  48. $match |= (ord($known_string[$i]) ^ ord($user_string[$i]));
  49. }
  50. return $match === 0;
  51. }
  52. }
  53. // Signed codes always have an time-to-live, by default 1 year (31536000 seconds).
  54. function create_signed_code($key, $message, $ttl = 31536000, $appended_data = '')
  55. {
  56. $expires = time() + $ttl;
  57. $body = $message . $expires . $appended_data;
  58. $signature = hash_hmac('sha256', $body, $key);
  59. return dechex($expires) . ':' . $signature . ':' . base64_url_encode($appended_data);
  60. }
  61. function verify_signed_code($key, $message, $code)
  62. {
  63. $code_parts = explode(':', $code, 3);
  64. if (count($code_parts) !== 3) {
  65. return false;
  66. }
  67. $expires = hexdec($code_parts[0]);
  68. if (time() > $expires) {
  69. return false;
  70. }
  71. $body = $message . $expires . base64_url_decode($code_parts[2]);
  72. $signature = hash_hmac('sha256', $body, $key);
  73. return hash_equals($signature, $code_parts[1]);
  74. }
  75. function verify_password($pass)
  76. {
  77. $hash_user = trim(preg_replace('/^https?:\/\//', '', USER_URL), '/');
  78. $hash = md5($hash_user . $pass . APP_KEY);
  79. return hash_equals(USER_HASH, $hash);
  80. }
  81. function filter_input_regexp($type, $variable, $regexp, $flags = null)
  82. {
  83. $options = array(
  84. 'options' => array('regexp' => $regexp)
  85. );
  86. if ($flags !== null) {
  87. $options['flags'] = $flags;
  88. }
  89. return filter_input(
  90. $type,
  91. $variable,
  92. FILTER_VALIDATE_REGEXP,
  93. $options
  94. );
  95. }
  96. function get_q_value($mime, $accept)
  97. {
  98. $fulltype = preg_replace('@^([^/]+\/).+$@', '$1*', $mime);
  99. $regex = implode(
  100. '',
  101. array(
  102. '/(?<=^|,)\s*(\*\/\*|',
  103. preg_quote($fulltype, '/'),
  104. '|',
  105. preg_quote($mime, '/'),
  106. ')\s*(?:[^,]*?;\s*q\s*=\s*([0-9.]+))?\s*(?:,|$)/'
  107. )
  108. );
  109. $out = preg_match_all($regex, $accept, $matches);
  110. $types = array_combine($matches[1], $matches[2]);
  111. if (array_key_exists($mime, $types)) {
  112. $q = $types[$mime];
  113. } elseif (array_key_exists($fulltype, $types)) {
  114. $q = $types[$fulltype];
  115. } elseif (array_key_exists('*/*', $types)) {
  116. $q = $types['*/*'];
  117. } else {
  118. return 0;
  119. }
  120. return $q === '' ? 1 : floatval($q);
  121. }
  122. // URL Safe Base64 per https://tools.ietf.org/html/rfc7515#appendix-C
  123. function base64_url_encode($string)
  124. {
  125. $string = base64_encode($string);
  126. $string = rtrim($string, '=');
  127. $string = strtr($string, '+/', '-_');
  128. return $string;
  129. }
  130. function base64_url_decode($string)
  131. {
  132. $string = strtr($string, '-_', '+/');
  133. $padding = strlen($string) % 4;
  134. if ($padding !== 0) {
  135. $string .= str_repeat('=', 4 - $padding);
  136. }
  137. $string = base64_decode($string);
  138. return $string;
  139. }
  140. if ((!defined('APP_URL') || APP_URL == '')
  141. || (!defined('APP_KEY') || APP_KEY == '')
  142. || (!defined('USER_HASH') || USER_HASH == '')
  143. || (!defined('USER_URL') || USER_URL == '')
  144. ) {
  145. error_page(
  146. 'Configuration Error',
  147. 'Endpoint not configured correctly, visit <a href="setup.php">setup.php</a> for instructions on how to set it up.'
  148. );
  149. }
  150. // First handle verification of codes.
  151. $code = filter_input_regexp(INPUT_POST, 'code', '@^[0-9a-f]+:[0-9a-f]{64}:@');
  152. if ($code !== null) {
  153. $redirect_uri = filter_input(INPUT_POST, 'redirect_uri', FILTER_VALIDATE_URL);
  154. $client_id = filter_input(INPUT_POST, 'client_id', FILTER_VALIDATE_URL);
  155. // Exit if there are errors in the client supplied data.
  156. if (!(is_string($code)
  157. && is_string($redirect_uri)
  158. && is_string($client_id)
  159. && verify_signed_code(APP_KEY, USER_URL . $redirect_uri . $client_id, $code))
  160. ) {
  161. error_page('Verification Failed', 'Given Code Was Invalid');
  162. }
  163. $response = array('me' => USER_URL);
  164. $code_parts = explode(':', $code, 3);
  165. if ($code_parts[2] !== '') {
  166. $response['scope'] = base64_url_decode($code_parts[2]);
  167. }
  168. // Accept header
  169. $accept_header = '*/*';
  170. if (isset($_SERVER['HTTP_ACCEPT']) && strlen($_SERVER['HTTP_ACCEPT']) > 0) {
  171. $accept_header = $_SERVER['HTTP_ACCEPT'];
  172. }
  173. // Find the q value for application/json.
  174. $json = get_q_value('application/json', $accept_header);
  175. // Find the q value for application/x-www-form-urlencoded.
  176. $form = get_q_value('application/x-www-form-urlencoded', $accept_header);
  177. // Respond in the correct way.
  178. if ($json === 0 && $form === 0) {
  179. error_page(
  180. 'No Accepted Response Types',
  181. 'The client accepts neither JSON nor Form encoded responses.',
  182. '406 Not Acceptable'
  183. );
  184. } elseif ($json >= $form) {
  185. header('Content-Type: application/json');
  186. exit(json_encode($response));
  187. } else {
  188. header('Content-Type: application/x-www-form-urlencoded');
  189. exit(http_build_query($response));
  190. }
  191. }
  192. // If this is not verification, collect all the client supplied data. Exit on errors.
  193. $me = filter_input(INPUT_GET, 'me', FILTER_VALIDATE_URL);
  194. $client_id = filter_input(INPUT_GET, 'client_id', FILTER_VALIDATE_URL);
  195. $redirect_uri = filter_input(INPUT_GET, 'redirect_uri', FILTER_VALIDATE_URL);
  196. $state = filter_input_regexp(INPUT_GET, 'state', '@^[\x20-\x7E]*$@');
  197. $response_type = filter_input_regexp(INPUT_GET, 'response_type', '@^(id|code)?$@');
  198. $scope = filter_input_regexp(INPUT_GET, 'scope', '@^([\x21\x23-\x5B\x5D-\x7E]+( [\x21\x23-\x5B\x5D-\x7E]+)*)?$@');
  199. if (!is_string($client_id)) { // client_id is either omitted or not a valid URL.
  200. error_page(
  201. 'Faulty Request',
  202. 'There was an error with the request. The "client_id" field is invalid.'
  203. );
  204. }
  205. if (!is_string($redirect_uri)) { // redirect_uri is either omitted or not a valid URL.
  206. error_page(
  207. 'Faulty Request',
  208. 'There was an error with the request. The "redirect_uri" field is invalid.'
  209. );
  210. }
  211. if ($state === false) { // state contains invalid characters.
  212. error_page(
  213. 'Faulty Request',
  214. 'There was an error with the request. The "state" field contains invalid data.'
  215. );
  216. }
  217. if ($response_type === false) { // response_type is given as something other than id or code.
  218. error_page(
  219. 'Faulty Request',
  220. 'There was an error with the request. The "response_type" field must be "code".'
  221. );
  222. }
  223. if ($scope === false) { // scope contains invalid characters.
  224. error_page(
  225. 'Faulty Request',
  226. 'There was an error with the request. The "scope" field contains invalid data.'
  227. );
  228. }
  229. if ($scope === '') { // scope is left empty.
  230. // Treat empty parameters as if omitted.
  231. $scope = null;
  232. }
  233. // If the user submitted a password, get ready to redirect back to the callback.
  234. $pass_input = filter_input(INPUT_POST, 'password', FILTER_UNSAFE_RAW);
  235. if ($pass_input !== null) {
  236. $csrf_code = filter_input(INPUT_POST, '_csrf', FILTER_UNSAFE_RAW);
  237. // Exit if the CSRF does not verify.
  238. if ($csrf_code === null || !verify_signed_code(APP_KEY, $client_id . $redirect_uri . $state, $csrf_code)) {
  239. error_page(
  240. 'Invalid CSF Code',
  241. 'Usually this means you took too long to log in. Please try again.'
  242. );
  243. }
  244. // Exit if the password does not verify.
  245. if (!verify_password($pass_input)) {
  246. // Optional logging for failed logins.
  247. //
  248. // Enabling this on shared hosting may not be a good idea if syslog
  249. // isn't private and accessible. Enable with caution.
  250. if (function_exists('syslog') && defined('SYSLOG_FAILURE') && SYSLOG_FAILURE === 'I understand') {
  251. syslog(LOG_CRIT, sprintf(
  252. 'IndieAuth: login failure from %s for %s',
  253. $_SERVER['REMOTE_ADDR'],
  254. $me
  255. ));
  256. }
  257. error_page('Login Failed', 'Invalid password.');
  258. }
  259. $scope = filter_input_regexp(INPUT_POST, 'scopes', '@^[\x21\x23-\x5B\x5D-\x7E]+$@', FILTER_REQUIRE_ARRAY);
  260. // Scopes are defined.
  261. if ($scope !== null) {
  262. // Exit if the scopes ended up with illegal characters or were not supplied as array.
  263. if ($scope === false || in_array(false, $scope, true)) {
  264. error_page('Invalid Scopes', 'The scopes provided contained illegal characters.');
  265. }
  266. // Turn scopes into a single string again.
  267. $scope = implode(' ', $scope);
  268. }
  269. $code = create_signed_code(APP_KEY, USER_URL . $redirect_uri . $client_id, 5 * 60, $scope);
  270. $final_redir = $redirect_uri;
  271. if (strpos($redirect_uri, '?') === false) {
  272. $final_redir .= '?';
  273. } else {
  274. $final_redir .= '&';
  275. }
  276. $parameters = array(
  277. 'code' => $code,
  278. 'me' => USER_URL
  279. );
  280. if ($state !== null) {
  281. $parameters['state'] = $state;
  282. }
  283. $final_redir .= http_build_query($parameters);
  284. // Optional logging for successful logins.
  285. //
  286. // Enabling this on shared hosting may not be a good idea if syslog
  287. // isn't private and accessible. Enable with caution.
  288. if (function_exists('syslog') && defined('SYSLOG_SUCCESS') && SYSLOG_SUCCESS === 'I understand') {
  289. syslog(LOG_INFO, sprintf(
  290. 'IndieAuth: login from %s for %s',
  291. $_SERVER['REMOTE_ADDR'],
  292. $me
  293. ));
  294. }
  295. // Redirect back.
  296. header('Location: ' . $final_redir, true, 302);
  297. exit();
  298. }
  299. // If neither password nor a code was submitted, we need to ask the user to authenticate.
  300. $csrf_code = create_signed_code(APP_KEY, $client_id . $redirect_uri . $state, 2 * 60);
  301. ?><!doctype html>
  302. <html>
  303. <head>
  304. <title>Login</title>
  305. <style>
  306. h1{text-align:center;margin-top:3%;}
  307. body {text-align:center;}
  308. fieldset, pre {width:400px; margin-left:auto; margin-right:auto;margin-bottom:50px; background-color:#FFC; min-height:1em;}
  309. fieldset {text-align:left;}
  310. .form-login{
  311. margin-left:auto;
  312. width:300px;
  313. margin-right:auto;
  314. text-align:center;
  315. margin-top:20px;
  316. border:solid 1px black;
  317. padding:20px;
  318. }
  319. .form-line{ margin:5px 0 0 0;}
  320. .submit{width:100%}
  321. .yellow{background-color:#FFC}
  322. </style>
  323. </head>
  324. <body>
  325. <form method="POST" action="">
  326. <h1>Authenticate</h1>
  327. <div>You are attempting to login with client <pre><?php echo htmlspecialchars($client_id); ?></pre></div>
  328. <?php if (strlen($scope) > 0) : ?>
  329. <div>It is requesting the following scopes, uncheck any you do not wish to grant:</div>
  330. <fieldset>
  331. <legend>Scopes</legend>
  332. <?php foreach (explode(' ', $scope) as $n => $checkbox) : ?>
  333. <div>
  334. <input id="scope_<?php echo $n; ?>" type="checkbox" name="scopes[]" value="<?php echo htmlspecialchars($checkbox); ?>" checked>
  335. <label for="scope_<?php echo $n; ?>"><?php echo $checkbox; ?></label>
  336. </div>
  337. <?php endforeach; ?>
  338. </fieldset>
  339. <?php endif; ?>
  340. <div>After login you will be redirected to <pre><?php echo htmlspecialchars($redirect_uri); ?></pre></div>
  341. <div class="form-login">
  342. <input type="hidden" name="_csrf" value="<?php echo $csrf_code; ?>" />
  343. <p class="form-line">
  344. Logging in as:<br />
  345. <span class="yellow"><?php echo htmlspecialchars(USER_URL); ?></span>
  346. </p>
  347. <div class="form-line">
  348. <label for="password">Password:</label><br />
  349. <input type="password" name="password" id="password" />
  350. </div>
  351. <div class="form-line">
  352. <input class="submit" type="submit" name="submit" value="Submit" />
  353. </div>
  354. </div>
  355. </form>
  356. </body>
  357. </html>