From 77f0f9ff1f1c54aef1e7370144df302d83118f70 Mon Sep 17 00:00:00 2001 From: Robert Kaiser Date: Fri, 28 Oct 2016 03:18:07 +0200 Subject: [PATCH] first step in making the authorize target work correctly, move check for secure connection into utils --- authorize.php | 52 +++++++++++++++++++++++++++++++++------------ authsystem.inc.php | 7 ++++++ authutils.php-class | 16 ++++++++++++++ index.php | 25 ++++++++++------------ token.php | 3 ++- 5 files changed, 75 insertions(+), 28 deletions(-) diff --git a/authorize.php b/authorize.php index 33d7d5e..68e3b94 100644 --- a/authorize.php +++ b/authorize.php @@ -3,37 +3,63 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -// Simple server based on https://bshaffer.github.io/oauth2-server-php-docs/cookbook +// Called e.g. as /authorize?response_type=code&client_id=testclient&state=f00bar&scope=email&redirect_uri=http%3A%2F%2Ffake.example.com%2F +// This either redirects to the redirect URL with errors or success added as GET parameters, +// or sends a HTML page asking for login / permission to scope (email is always granted in this system but not always for OAuth2 generically) +// or sends errors as a JSOn document (hopefully shouldn't but seen that in testing). // Include the common auth system files (including the OAuth2 Server object). require_once(__DIR__.'/authsystem.inc.php'); +$errors = $utils->checkForSecureConnection(); + $request = OAuth2\Request::createFromGlobals(); $response = new OAuth2\Response(); -// validate the authorize request +// Validate the authorize request. if (!$server->validateAuthorizeRequest($request, $response)) { - $response->send(); - die; + $response->send(); + exit(); } -// display an authorization form + +// Display an authorization form. if (empty($_POST)) { - exit(' -
-
- - -
'); + // Start HTML document as a DOM object. + extract(ExtendedDocument::initHTML5()); // sets $document, $html, $head, $title, $body + $document->formatOutput = true; // we want a nice output + $style = $head->appendElement('link'); + $style->setAttribute('rel', 'stylesheet'); + $style->setAttribute('href', 'authsystem.css'); + $head->appendJSFile('authsystem.js'); + $title->appendText('Authorization Request | KaiRo.at'); + $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server'); + + $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.')); + $para->setAttribute('id', 'jswarning'); + $para->setAttribute('class', 'warn'); + + $form = $body->appendForm('', 'POST', 'authform'); + $form->setAttribute('id', 'authform'); + $form->appendElement('p', sprintf(_('Do you authorize %s to access %s?'), $request->query['client_id'], $request->query['scope'])); + $submit = $form->appendInputSubmit(_('yes')); + $submit->setAttribute('name', 'authorized'); + $form->appendText(' '); + $submit = $form->appendInputSubmit(_('no')); + $submit->setAttribute('name', 'authorized'); + // Send HTML to client. + print($document->saveHTML()); + exit(); } -// print the authorization code if the user has authorized your client +// Handle authorize request, forwarding code in GET parameters if the user has authorized your client. $is_authorized = ($_POST['authorized'] === 'yes'); $server->handleAuthorizeRequest($request, $response, $is_authorized); +/* For testing only if ($is_authorized) { // this is only here so that you get to see your code in the cURL request. Otherwise, we'd redirect back to the client $code = substr($response->getHttpHeader('Location'), strpos($response->getHttpHeader('Location'), 'code=')+5, 40); exit("SUCCESS! Authorization Code: $code"); } +*/ $response->send(); - ?> diff --git a/authsystem.inc.php b/authsystem.inc.php index 2c98f6d..8b26e4f 100644 --- a/authsystem.inc.php +++ b/authsystem.inc.php @@ -3,6 +3,13 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ +/* + Some resources for how to store passwords: + - https://blog.mozilla.org/webdev/2012/06/08/lets-talk-about-password-storage/ + - https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines + oauth-server-php: https://bshaffer.github.io/oauth2-server-php-docs/cookbook +*/ + // error reporting (for testing) ini_set('display_errors', 1); error_reporting(E_ALL); diff --git a/authutils.php-class b/authutils.php-class index 729a2e9..555721e 100755 --- a/authutils.php-class +++ b/authutils.php-class @@ -15,6 +15,9 @@ class AuthUtils { // public $db // A PDO database object for interaction. // + // public $running_on_localhost + // A boolean telling if the system is running on localhost (where https is not required). + // // private $pwd_cost // The cost parameter for use with PHP password_hash function. // @@ -25,6 +28,9 @@ class AuthUtils { // function log($code, $additional_info) // Log an entry for admin purposes, with a code and some additional info. // + // function checkForSecureConnection() + // Check is the connection is secure and return an array of error messages (empty if it's secure). + // // function checkPasswordConstraints($new_password, $user_email) // Check password constraints and return an array of error messages (empty if all constraints are met). // @@ -55,6 +61,7 @@ class AuthUtils { function __construct($settings, $db) { // *** constructor *** $this->db = $db; + $this->running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']); if (array_key_exists('pwd_cost', $settings)) { $this->pwd_cost = $settings['pwd_cost']; } @@ -64,6 +71,7 @@ class AuthUtils { } public $db = null; + public $running_on_localhost = false; private $pwd_cost = 10; private $pwd_nonces = array(); @@ -74,6 +82,14 @@ class AuthUtils { } } + function checkForSecureConnection() { + $errors = array(); + if (($_SERVER['SERVER_PORT'] != 443) && !$this->running_on_localhost) { + $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.'); + } + return $errors; + } + function checkPasswordConstraints($new_password, $user_email) { $errors = array(); if ($new_password != trim($new_password)) { diff --git a/index.php b/index.php index 94812dc..841333b 100644 --- a/index.php +++ b/index.php @@ -19,10 +19,7 @@ $head->appendJSFile('authsystem.js'); $title->appendText('KaiRo.at Authentication Server'); $h1 = $body->appendElement('h1', 'KaiRo.at Authentication Server'); -$running_on_localhost = preg_match('/^((.+\.)?localhost|127\.0\.0\.\d+)$/', $_SERVER['SERVER_NAME']); -if (($_SERVER['SERVER_PORT'] != 443) && !$running_on_localhost) { - $errors[] = _('You are not accessing this site on a secure connection, so authentication doesn\'t work.'); -} +$errors += $utils->checkForSecureConnection(); $para = $body->appendElement('p', _('This login system does not work without JavaScript. Please activate JavaScript for this site to log in.')); $para->setAttribute('id', 'jswarning'); @@ -77,7 +74,7 @@ if (!count($errors)) { // Log user in - update session key for that, see https://wiki.mozilla.org/WebAppSec/Secure_Coding_Guidelines#Login $utils->log('login', 'user: '.$user['id']); $sesskey = $utils->createSessionKey(); - setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. + setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. // If the session has a user set, create a new one - otherwise take existing session entry. if (intval($session['user'])) { $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`, `user`, `logged_in`) VALUES (:sesskey, :expire, :userid, TRUE);'); @@ -150,7 +147,7 @@ if (!count($errors)) { $mail->addMailText(sprintf(_('This email address, %s, has been used for registration on "%s".'), $user['email'], _('KaiRo.at Authentication Service'))."\n\n"); $mail->addMailText(_('Please confirm that registration by clicking the following link (or calling it up in your browser):')."\n"); - $mail->addMailText(($running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true) + $mail->addMailText(($utils->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true) .'?email='.rawurlencode($user['email']).'&verification_code='.rawurlencode($user['verify_hash'])."\n\n"); $mail->addMailText(_('With this confirmation, you accept that we handle your data for the purpose of logging you into other websites when you request that.')."\n"); $mail->addMailText(_('Those websites will get to know your email address but not your password, which we store securely.')."\n"); @@ -188,7 +185,7 @@ if (!count($errors)) { $mail->addMailText(sprintf(_('A request for setting a new password for this email address, %s, has been submitted on "%s".'), $user['email'], _('KaiRo.at Authentication Service'))."\n\n"); $mail->addMailText(_('You can set a new password by clicking the following link (or calling it up in your browser):')."\n"); - $mail->addMailText(($running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true) + $mail->addMailText(($utils->running_on_localhost?'http':'https').'://'.$_SERVER['SERVER_NAME'].strstr($_SERVER['REQUEST_URI'], '?', true) .'?email='.rawurlencode($user['email']).'&reset_code='.rawurlencode($resetcode)."\n\n"); $mail->addMailText(_('If you do not call this confirmation link within 1 hour, this link expires and the existing password is being kept in place.')."\n\n"); $mail->addMailText(sprintf(_('The %s team'), 'KaiRo.at')); @@ -317,7 +314,7 @@ if (!count($errors)) { if (is_null($session)) { // Create new session and set cookie. $sesskey = $utils->createSessionKey(); - setcookie('sessionkey', $sesskey, 0, "", "", !$running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. + setcookie('sessionkey', $sesskey, 0, "", "", !$utils->running_on_localhost, true); // Last two params are secure and httponly, secure is not set on localhost. $result = $db->prepare('INSERT INTO `auth_sessions` (`sesskey`, `time_expire`) VALUES (:sesskey, :expire);'); $result->execute(array(':sesskey' => $sesskey, ':expire' => gmdate('Y-m-d H:i:s', strtotime('+5 minutes')))); // After insert, actually fetch the session row from the DB so we have all values. @@ -347,7 +344,7 @@ if (!count($errors)) { elseif ($pagetype == 'resetstart') { $para = $body->appendElement('p', _('If you forgot your password or didn\'t receive the registration confirmation, please enter your email here.')); $para->setAttribute('class', ''); - $form = $body->appendForm('?reset', 'POST', 'resetform'); + $form = $body->appendForm('./?reset', 'POST', 'resetform'); $form->setAttribute('id', 'loginform'); $form->setAttribute('class', 'loginarea hidden'); $ulist = $form->appendElement('ul'); @@ -364,7 +361,7 @@ if (!count($errors)) { elseif ($pagetype == 'resetpwd') { $para = $body->appendElement('p', sprintf(_('You can set a new password for %s here.'), $user['email'])); $para->setAttribute('class', ''); - $form = $body->appendForm('?', 'POST', 'newpwdform'); + $form = $body->appendForm('./', 'POST', 'newpwdform'); $form->setAttribute('id', 'loginform'); $form->setAttribute('class', 'loginarea hidden'); $ulist = $form->appendElement('ul'); @@ -399,9 +396,9 @@ if (!count($errors)) { $ulist = $div->appendElement('ul'); $ulist->setAttribute('class', 'flat'); $litem = $ulist->appendElement('li'); - $link = $litem->appendLink('?logout', _('Log out')); + $link = $litem->appendLink('./?logout', _('Log out')); $litem = $ulist->appendElement('li'); - $litem->appendLink('?reset', _('Set new password')); + $litem->appendLink('./?reset', _('Set new password')); } else { // not logged in if ($pagetype == 'verification_done') { @@ -412,7 +409,7 @@ if (!count($errors)) { $para = $body->appendElement('p', _('Your password has successfully been reset. You can log in now with the new password.')); $para->setAttribute('class', 'resetinfo done'); } - $form = $body->appendForm('?', 'POST', 'loginform'); + $form = $body->appendForm('./', 'POST', 'loginform'); $form->setAttribute('id', 'loginform'); $form->setAttribute('class', 'loginarea hidden'); $ulist = $form->appendElement('ul'); @@ -429,7 +426,7 @@ if (!count($errors)) { $inptxt->setAttribute('placeholder', _('Password')); $inptxt->setAttribute('class', 'login'); $litem = $ulist->appendElement('li'); - $litem->appendLink('?reset', _('Forgot password?')); + $litem->appendLink('./?reset', _('Forgot password?')); $litem = $ulist->appendElement('li'); $cbox = $litem->appendInputCheckbox('remember', 'login_remember', 'true', false); $cbox->setAttribute('class', 'logincheck'); diff --git a/token.php b/token.php index 44fcdc8..e3cf8ff 100644 --- a/token.php +++ b/token.php @@ -3,7 +3,8 @@ * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ -// Simple server based on https://bshaffer.github.io/oauth2-server-php-docs/cookbook +// Called with e.g. curl .../token -d 'grant_type=authorization_code&client_id=testclient&client_secret=testpass&code=&state=f00bar&redirect_uri=http%3A%2F%2Ffake.example.com%2F' +// Response is always JSON. // Include the common auth system files (including the OAuth2 Server object). require_once(__DIR__.'/authsystem.inc.php'); -- 2.35.3