diff --git a/class-Session.php b/class-Session.php index 44d5724..f64bc27 100644 --- a/class-Session.php +++ b/class-Session.php @@ -1,335 +1,315 @@ . // 60s * 60m * 24h * 7d define_default( 'SESSION_DURATION', 604800 ); // the default user logged-in class define_default( 'SESSIONUSER_CLASS', 'Sessionuser' ); // the default algorithm for the User fingerprint define_default( 'SESSION_FINGERPRINT_ALGO', 'sha256' ); -// the default pepper for the User fingerprint -define_default( 'SESSION_FINGERPRINT_PEPP', 'just-something' ); - -// the default pepper for the User fingerprint -define_default( 'SESSION_FINGERPRINT_SALT', 'just-something' ); - /** * Session handler * * Note that actually we do NOT need server sessions <3 */ class Session { /** * User currently logged * * @var Sessionuser */ private $user = null; /** * Are the cookies tobe validated? * * @var bool */ private $mustValidate = true; /** - * Last CSRF generated to the User - * - * Note that this is populated just in the login process. - * Note that when sending cookies, the $_COOKIE['csrf'] variable is still empty. + * Last CSRF generated * * @var string */ private $csrf; + /** + * Constructor + */ + public function __construct() { + // remember the existing CSRF if available + if( isset( $_COOKIE['csrf'] ) ) { + $this->csrf = $_COOKIE['csrf']; + } + } + /** * Get the singleton instance * * @return self */ public static function instance() { static $me = false; if( ! $me ) { $me = new self(); } return $me; } /** * Is the user logged? * * @return boolean */ public function isLogged() { return is_object( $this->getUser() ); } /** * Get the currently logged-in user * * @return Sessionuser */ public function getUser() { if( $this->mustValidate ) { $this->validate(); } return $this->user; } /* * Login statuses */ const OK = 0; const LOGIN_FAILED = 1; const ALREADY_LOGGED = 2; const EMPTY_USER_UID = 4; const EMPTY_USER_PASSWORD = 8; const USER_DISABLED = 64; /** * Do a login * * @param int $status int Login status * @param string $uid User UID (if not specified is the 'user_uid' POST field * @param string $pwd User password (if not specified is the 'user_password' POST field * @return bool */ public function login( & $status = null, $uid = null, $pwd = null ) { // already logged if( $this->isLogged() ) { $status = self::ALREADY_LOGGED; return true; } // UID from function or POST if( $uid === null && isset( $_POST['user_uid'] ) ) { $uid = $_POST['user_uid']; } // password from parameter or POST if( $pwd === null && isset( $_POST['user_password'] ) ) { $pwd = $_POST['user_password']; } // no uid no party if( empty( $uid ) ) { $status = self::EMPTY_USER_UID; return false; } // no password no party if( empty( $pwd ) ) { $status = self::EMPTY_USER_PASSWORD; return false; } // check if the user exists (note that the user class can be customized) $userClass = SESSIONUSER_CLASS; $user = $userClass::factoryFromLogin( $uid, $pwd ) ->queryRow(); // check if user exists if( ! $user ) { $status = self::LOGIN_FAILED; self::failed( $userClass::sanitizeUID( $uid ), 'POST' ); return false; } // check if user is active if( ! $user->isSessionuserActive() ) { $status = self::USER_DISABLED; return false; } // mark as logged $this->user = $user; // mark cookies as already validated $this->mustValidate = false; // pass login status $status = self::OK; - // store the CSRF - $this->csrf = $this->generateCSRF(); - // set cookies + $this->setCookie( 'user_uid', $user->getSessionuserUID(), false ); + $this->setCookie( 'token', $user->generateSessionuserCookieToken(), true ); + + // it's a good moment to renew the anti-CSRF token + $this->renewCSRF(); + + return true; + } + + /** + * Set a cookie + * + * @param string $name Cookie name + * @param string $value Cookie value + * @param boolean $httponly When true do not expose via JavaScript + */ + private function setCookie( $name, $value, $httponly ) { $duration = time() + SESSION_DURATION; $path = ROOT . _; $force_https = PROTOCOL === 'https://'; - setcookie( 'user_uid', $user->getSessionuserUID(), $duration, $path, '', $force_https, false ); - setcookie( 'token', $user->generateSessionuserCookieToken(), $duration, $path, '', $force_https, true ); - setcookie( 'csrf', $this->csrf, $duration, $path, '', $force_https, true ); - - return true; + setcookie( $name, $value, $duration, $path, '', $force_https, $httponly ); } /** - * Validate the user session from cookies + * Validate the session */ private function validate() { // do not call this twice $this->mustValidate = false; // no cookies no party if( !isset( $_COOKIE['user_uid'], $_COOKIE['token'] ) ) { return; } // retrieve the user just from the username (then will check the password) $userClass = SESSIONUSER_CLASS; $user = $userClass::factoryFromUID( $_COOKIE['user_uid'] ) ->queryRow(); // missing user or inactive if( !$user || !$user->isSessionuserActive() ) { return $this->destroy(); } // check if the token is OK if( $_COOKIE['token'] !== $user->generateSessionuserCookieToken() ) { self::failed( $userClass::sanitizeUID( $_COOKIE['user_uid'] ), 'cookies' ); return $this->destroy(); } // now the user is logged $this->user = $user; } /** * Destroy the session */ public function destroy() { $invalidate = time() - 8000; $path = ROOT . _; // try to destroy the cookies if( !headers_sent() ) { setcookie( 'user_uid', 'asd', $invalidate, $path ); setcookie( 'token', 'asd', $invalidate, $path ); setcookie( 'csrf', 'asd', $invalidate, $path ); } - $this->csrf = null; - // logout $this->user = null; $this->mustValidate = false; - } - /** - * Get the CSRF token of the current user - * - * If the user is logged-in, the CSRF is a cookie. - * If the user is not logged-in, the CSRF is generated from his environment fingerprint. - * - * @return string - */ - public function getCSRF() { - if( $this->isLogged() ) { - if( isset( $_COOKIE['csrf'] ) ) { - return $_COOKIE['csrf']; - } - if( isset( $this->csrf ) ) { - return $this->csrf; - } - error( 'missing CSRF cookie from User ID ' . $this->user->getSessionuserID() ); - } - - // for non logged-in users the CSRF it's just the fingerprint - return $this->getFingerprint(); + // unset accordingly to the cookie + $this->csrf = null; } /** - * Get the fingerprint of this User + * Get the CSRF token (or send a new one) * * @return string */ - public function getFingerprint() { - $fingerprint = ''; - - // Some browser fields that can identify the client. - // An attacker should know the exact version of the browser, it's language - // configuration setting and the IP of the client to generate its fingerprint. - $infos = [ - 'REMOTE_ADDR', - 'HTTP_USER_AGENT', - 'HTTP_ACCEPT_LANGUAGE' - ]; - foreach( $infos as $info ) { - if( isset( $_SERVER[ $info ] ) ) { - $fingerprint .= $_SERVER[ $info ]; - } + public function getCSRF() { + if( empty( $this->csrf ) ) { + $this->renewCSRF(); } - $fingerprint_burger = SESSION_FINGERPRINT_PEPP . $fingerprint . SESSION_FINGERPRINT_SALT; - return hash( SESSION_FINGERPRINT_ALGO, $fingerprint_burger ); + return $this->csrf; } /** - * Print a form action field with the CSRF + * Print a form action field with the anti-CSRF token * - * @param string $action + * @param string $action Form action (e.g. 'save-user') */ public function formActionWithCSRF( $action ) { - echo HTML::input( 'hidden', 'action', $action ); - echo HTML::input( 'hidden', 'csrf', $this->getCSRF() ); + echo HTML::input( 'hidden', 'csrf', $this->getCSRF() ); + echo HTML::input( 'hidden', 'action', $action ); } /** - * Check if a form action is valid (with the related CSRF) + * Check if a form action is valid (with the related anti-CSRF token) * * @param string $action * @return boolean */ public function validateActionAndCSRF( $action ) { $csrf = $this->getCSRF(); return isset( $_POST['action'], $_POST['csrf'] ) && $_POST['action'] === $action && $_POST['csrf'] === $csrf; } /** - * Generate a new CSRF token + * Generate a new anti-CSRF token + * + * This will also send a new COOKIE. * - * @param int $bytes How much bytes to generate + * @param int $bytes How much random bytes for the anti-CSRF token * @return string */ - private function generateCSRF( $bytes = 8 ) { - return bin2hex( openssl_random_pseudo_bytes( $bytes ) ); + public function renewCSRF( $bytes = 8 ) { + $this->csrf = bin2hex( openssl_random_pseudo_bytes( $bytes ) ); + $this->setCookie( 'csrf', $this->csrf, true ); + return $this->csrf; } /** * Log in syslog a login fail * * @param $uid string * @param $from string */ public static function failed( $uid, $from ) { error_log( sprintf( "Login failed by '%s' using %s", $uid, $from ) ); } } diff --git a/functions.php b/functions.php index ae0c4f9..cb13421 100644 --- a/functions.php +++ b/functions.php @@ -1,1124 +1,1131 @@ . /** * Check if the user do not want to be tracked * * See the HTTP 'DNT' header. * * @return boolean */ function do_not_track() { return isset( $_SERVER['HTTP_DNT'] ) && $_SERVER['HTTP_DNT'] === '1'; } /* * Configuration helpers * * Shortcuts useful when you declare a configuration file. */ /** * Define a constant if it does not exist * * @param string $name Constant name * @param string $value Constant value */ function define_default( $name, $value ) { defined( $name ) or define( $name, $value ); } /* * Template helpers * * Shortcuts useful when you build a page */ /** * Return a ' selected="selected"' HTML attribute under some circumstances * * @param mixed $helper If this is the only arg, return * @param mixed $current If this matches $helper, return * @param bool $force If this is true, return */ function selected( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_attribute_when_matching( 'selected', 'selected', $helper, $current, $force); } /** * Return a ' checked="checked"' HTML attribute under some circumstances * * This is useful for the HTML tag. * * @param mixed $helper If this is the only arg, return * @param mixed $current If this matches $helper, return * @param bool $force If this is true, return */ function checked( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_attribute_when_matching( 'checked', 'checked', $helper, $current, $force); } /** * Return a ' disabled="disabled"' HTML attribute under some circumstances * * @param mixed $helper If this is the only arg, return * @param mixed $current If this matches $helper, return * @param bool $force If this is true, return */ function disabled( $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { return html_attribute_when_matching( 'disabled', 'disabled', $helper, $current, $force ); } /** * Return an HTML attribute under some circumstances * * @param string $attribute HTML attribute name e.g. 'disabled' * @param string $value HTML attribute value e.g. * @param mixed $helper If this is the only arg, return * @param mixed $current If this matches $helper, return * @param bool $force If this is true, return */ function html_attribute_when_matching( $attribute, $value, $helper = PHP_INT_MAX, $current = PHP_INT_MAX, $force = false ) { if( $helper === $current || $helper && PHP_INT_MAX === $current || $force ) { return HTML::property( $attribute, $value ); } return ''; } /** * Get an HTML attribute ' value="$v"' * * The value will be sanitized. * * @param string $v * @return string */ function value( $v ) { return HTML::property( 'value', $v ); } /** * Shortcut for htmlentities() * * Return an HTML-sanitized untrusted string to be safe from XSS. * * @param string $s e.g. 'Hello