3 * Check for valid user via login form or stored cookie. Returns true or an error message
6 function yourls_is_valid_user() {
7 // Allow plugins to short-circuit the whole function
8 $pre = yourls_apply_filter( 'shunt_is_valid_user', null );
13 // $unfiltered_valid : are credentials valid? Boolean value. It's "unfiltered" to allow plugins to eventually filter it.
14 $unfiltered_valid = false;
17 if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) {
18 yourls_do_action( 'logout' );
19 yourls_store_cookie( null );
20 return yourls__( 'Logged out successfully' );
23 // Check cookies or login request. Login form has precedence.
25 yourls_do_action( 'pre_login' );
27 // Determine auth method and check credentials
29 // API only: Secure (no login or pwd) and time limited token
30 // ?timestamp=12345678&signature=md5(totoblah12345678)
32 isset( $_REQUEST['timestamp'] ) && !empty($_REQUEST['timestamp'] ) &&
33 isset( $_REQUEST['signature'] ) && !empty($_REQUEST['signature'] )
36 yourls_do_action( 'pre_login_signature_timestamp' );
37 $unfiltered_valid = yourls_check_signature_timestamp();
41 // API only: Secure (no login or pwd)
42 // ?signature=md5(totoblah)
44 !isset( $_REQUEST['timestamp'] ) &&
45 isset( $_REQUEST['signature'] ) && !empty( $_REQUEST['signature'] )
48 yourls_do_action( 'pre_login_signature' );
49 $unfiltered_valid = yourls_check_signature();
53 // API or normal: login with username & pwd
54 ( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] )
55 && !empty( $_REQUEST['username'] ) && !empty( $_REQUEST['password'] ) )
57 yourls_do_action( 'pre_login_username_password' );
58 $unfiltered_valid = yourls_check_username_password();
62 // Normal only: cookies
64 isset( $_COOKIE[ yourls_cookie_name() ] ) )
66 yourls_do_action( 'pre_login_cookie' );
67 $unfiltered_valid = yourls_check_auth_cookie();
70 // Regardless of validity, allow plugins to filter the boolean and have final word
71 $valid = yourls_apply_filter( 'is_valid_user', $unfiltered_valid );
75 yourls_do_action( 'login' );
77 // (Re)store encrypted cookie if needed
78 if ( !yourls_is_API() ) {
79 yourls_store_cookie( YOURLS_USER );
81 // Login form : redirect to requested URL to avoid re-submitting the login form on page reload
82 if( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) && isset( $_SERVER['REQUEST_URI'] ) ) {
83 $url = $_SERVER['REQUEST_URI'];
84 yourls_redirect( $url );
93 yourls_do_action( 'login_failed' );
95 if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) {
96 return yourls__( 'Invalid username or password' );
98 return yourls__( 'Please log in' );
103 * Check auth against list of login=>pwd. Sets user if applicable, returns bool
106 function yourls_check_username_password() {
107 global $yourls_user_passwords;
108 if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {
109 yourls_set_user( $_REQUEST['username'] );
116 * Check a submitted password sent in plain text against stored password which can be a salted hash
119 function yourls_check_password_hash( $user, $submitted_password ) {
120 global $yourls_user_passwords;
122 if( !isset( $yourls_user_passwords[ $user ] ) )
125 if ( yourls_has_phpass_password( $user ) ) {
126 // Stored password is hashed with phpass
127 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] );
128 $hash = str_replace( '!', '$', $hash );
129 return ( yourls_phpass_check( $submitted_password, $hash ) );
130 } else if( yourls_has_md5_password( $user ) ) {
131 // Stored password is a salted md5 hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>"
132 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] );
133 return( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
135 // Password stored in clear text
136 return( $yourls_user_passwords[ $user ] == $submitted_password );
141 * Overwrite plaintext passwords in config file with phpassed versions.
144 * @param string $config_file Full path to file
145 * @return true if overwrite was successful, an error message otherwise
147 function yourls_hash_passwords_now( $config_file ) {
148 if( !is_readable( $config_file ) )
149 return 'cannot read file'; // not sure that can actually happen...
151 if( !is_writable( $config_file ) )
152 return 'cannot write file';
154 // Include file to read value of $yourls_user_passwords
155 // Temporary suppress error reporting to avoid notices about redeclared constants
156 $errlevel = error_reporting();
157 error_reporting( 0 );
158 require $config_file;
159 error_reporting( $errlevel );
161 $configdata = file_get_contents( $config_file );
162 if( $configdata == false )
163 return 'could not read file';
165 $to_hash = 0; // keep track of number of passwords that need hashing
166 foreach ( $yourls_user_passwords as $user => $password ) {
167 if ( !yourls_has_phpass_password( $user ) && !yourls_has_md5_password( $user ) ) {
169 $hash = yourls_phpass_hash( $password );
170 // PHP would interpret $ as a variable, so replace it in storage.
171 $hash = str_replace( '$', '!', $hash );
173 $pattern = "/[$quotes]${user}[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '/' ) . "[$quotes]/";
174 $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ ";
176 $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
177 // There should be exactly one replacement. Otherwise, fast fail.
179 yourls_debug_log( "Problem with preg_replace for password hash of user $user" );
180 return 'preg_replace problem';
186 return 0; // There was no password to encrypt
188 $success = file_put_contents( $config_file, $configdata );
189 if ( $success === FALSE ) {
190 yourls_debug_log( 'Failed writing to ' . $config_file );
191 return 'could not write file';
197 * Hash a password using phpass
200 * @param string $password password to hash
201 * @return string hashed password
203 function yourls_phpass_hash( $password ) {
204 $hasher = yourls_phpass_instance();
205 return $hasher->HashPassword( $password );
209 * Check a clear password against a phpass hash
212 * @param string $password clear (eg submitted in a form) password
213 * @param string $hash hash supposedly generated by phpass
214 * @return bool true if the hash matches the password once hashed by phpass, false otherwise
216 function yourls_phpass_check( $password, $hash ) {
217 $hasher = yourls_phpass_instance();
218 return $hasher->CheckPassword( $password, $hash );
222 * Helper function: create new instance or return existing instance of phpass class
225 * @param int $iteration iteration count - 8 is default in phpass
226 * @param bool $portable flag to force portable (cross platform and system independant) hashes - false to use whatever the system can do best
227 * @return object a PasswordHash instance
229 function yourls_phpass_instance( $iteration = 8, $portable = false ) {
230 $iteration = yourls_apply_filter( 'phpass_new_instance_iteration', $iteration );
231 $portable = yourls_apply_filter( 'phpass_new_instance_portable', $portable );
233 if( !class_exists( 'PasswordHash' ) ) {
234 require_once( YOURLS_INC.'/phpass/PasswordHash.php' );
237 static $instance = false;
238 if( $instance == false ) {
239 $instance = new PasswordHash( $iteration, $portable );
247 * Check to see if any passwords are stored as cleartext.
250 * @return bool true if any passwords are cleartext
252 function yourls_has_cleartext_passwords() {
253 global $yourls_user_passwords;
254 foreach ( $yourls_user_passwords as $user => $pwdata ) {
255 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) {
263 * Check if a user has a hashed password
265 * Check if a user password is 'md5:[38 chars]'.
266 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
269 * @param string $user user login
270 * @return bool true if password hashed, false otherwise
272 function yourls_has_md5_password( $user ) {
273 global $yourls_user_passwords;
274 return( isset( $yourls_user_passwords[ $user ] )
275 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
276 && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
281 * Check if a user's password is hashed with PHPASS.
283 * Check if a user password is 'phpass:[lots of chars]'.
284 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
287 * @param string $user user login
288 * @return bool true if password hashed with PHPASS, otherwise false
290 function yourls_has_phpass_password( $user ) {
291 global $yourls_user_passwords;
292 return( isset( $yourls_user_passwords[ $user ] )
293 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
298 * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
301 function yourls_check_auth_cookie() {
302 global $yourls_user_passwords;
303 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
304 if ( yourls_salt( $valid_user ) == $_COOKIE[ yourls_cookie_name() ] ) {
305 yourls_set_user( $valid_user );
313 * Check auth against signature and timestamp. Sets user if applicable, returns bool
317 * @return bool False if signature or timestamp missing or invalid, true if valid
319 function yourls_check_signature_timestamp() {
320 if( !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] )
321 OR !isset( $_REQUEST['timestamp'] ) OR empty( $_REQUEST['timestamp'] )
325 // Timestamp in PHP : time()
326 // Timestamp in JS: parseInt(new Date().getTime() / 1000)
328 // Check signature & timestamp against all possible users
329 global $yourls_user_passwords;
330 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
333 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
335 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
338 yourls_check_timestamp( $_REQUEST['timestamp'] )
340 yourls_set_user( $valid_user );
345 // Signature doesn't match known user
350 * Check auth against signature. Sets user if applicable, returns bool
353 * @return bool False if signature missing or invalid, true if valid
355 function yourls_check_signature() {
356 if( !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] ) )
359 // Check signature against all possible users
360 global $yourls_user_passwords;
361 foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
362 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
363 yourls_set_user( $valid_user );
368 // Signature doesn't match known user
373 * Generate secret signature hash
376 function yourls_auth_signature( $username = false ) {
377 if( !$username && defined('YOURLS_USER') ) {
378 $username = YOURLS_USER;
380 return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
384 * Check if timestamp is not too old
387 function yourls_check_timestamp( $time ) {
389 // Allow timestamp to be a little in the future or the past -- see Issue 766
390 return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
394 * Store new cookie. No $user will delete the cookie.
397 function yourls_store_cookie( $user = null ) {
400 $time = time() - 3600;
402 global $yourls_user_passwords;
403 if( isset($yourls_user_passwords[$user]) ) {
404 $pass = $yourls_user_passwords[$user];
406 die( 'Stealing cookies?' ); // This should never happen
408 $time = time() + YOURLS_COOKIE_LIFE;
411 $domain = yourls_apply_filter( 'setcookie_domain', parse_url( YOURLS_SITE, 1 ) );
412 $secure = yourls_apply_filter( 'setcookie_secure', yourls_is_ssl() );
413 $httponly = yourls_apply_filter( 'setcookie_httponly', true );
415 // Some browsers refuse to store localhost cookie
416 if ( $domain == 'localhost' )
419 if ( !headers_sent( $filename, $linenum ) ) {
420 // Set httponly if the php version is >= 5.2.0
421 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
422 setcookie( yourls_cookie_name(), yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
424 setcookie( yourls_cookie_name(), yourls_salt( $user ), $time, '/', $domain, $secure );
427 // For some reason cookies were not stored: action to be able to debug that
428 yourls_do_action( 'setcookie_failed', $user );
429 yourls_debug_log( "Could not store cookie: headers already sent in $filename on line $linenum" );
437 function yourls_set_user( $user ) {
438 if( !defined( 'YOURLS_USER' ) )
439 define( 'YOURLS_USER', $user );
443 * Get YOURLS cookie name
445 * The name is unique for each install, to prevent mismatch between sho.rt and very.sho.rt -- see #1673
447 * TODO: when multi user is implemented, the whole cookie stuff should be reworked to allow storing multiple users
450 * @return string unique cookie name for a given YOURLS site
452 function yourls_cookie_name() {
453 return 'yourls_' . yourls_salt( YOURLS_SITE );