]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-auth.php
Make yourls_hash_passwords_now() independent from globals
[Github/YOURLS.git] / includes / functions-auth.php
1 <?php
2 /**
3  * Check for valid user via login form or stored cookie. Returns true or an error message
4  *
5  */
6 function yourls_is_valid_user() {
7         static $valid = false;
8         
9         if( $valid )
10                 return true;
11                 
12         // Allow plugins to short-circuit the whole function
13         $pre = yourls_apply_filter( 'shunt_is_valid_user', null );
14         if ( null !== $pre ) {
15                 $valid = ( $pre === true ) ;
16                 return $pre;
17         }
18         
19         // $unfiltered_valid : are credentials valid? Boolean value. It's "unfiltered" to allow plugins to eventually filter it.
20         $unfiltered_valid = false;
21
22         // Logout request
23         if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) {
24                 yourls_do_action( 'logout' );
25                 yourls_store_cookie( null );
26                 return yourls__( 'Logged out successfully' );
27         }
28         
29         // Check cookies or login request. Login form has precedence.
30
31         yourls_do_action( 'pre_login' );
32
33         // Determine auth method and check credentials
34         if
35                 // API only: Secure (no login or pwd) and time limited token
36                 // ?timestamp=12345678&signature=md5(totoblah12345678)
37                 ( yourls_is_API() &&
38                   isset( $_REQUEST['timestamp'] ) && !empty($_REQUEST['timestamp'] ) &&
39                   isset( $_REQUEST['signature'] ) && !empty($_REQUEST['signature'] )
40                 )
41                 {
42                         yourls_do_action( 'pre_login_signature_timestamp' );
43                         $unfiltered_valid = yourls_check_signature_timestamp();
44                 }
45                 
46         elseif
47                 // API only: Secure (no login or pwd)
48                 // ?signature=md5(totoblah)
49                 ( yourls_is_API() &&
50                   !isset( $_REQUEST['timestamp'] ) &&
51                   isset( $_REQUEST['signature'] ) && !empty( $_REQUEST['signature'] )
52                 )
53                 {
54                         yourls_do_action( 'pre_login_signature' );
55                         $unfiltered_valid = yourls_check_signature();
56                 }
57         
58         elseif
59                 // API or normal: login with username & pwd
60                 ( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] )
61                   && !empty( $_REQUEST['username'] ) && !empty( $_REQUEST['password']  ) )
62                 {
63                         yourls_do_action( 'pre_login_username_password' );
64                         $unfiltered_valid = yourls_check_username_password();
65                 }
66         
67         elseif
68                 // Normal only: cookies
69                 ( !yourls_is_API() && 
70                   isset( $_COOKIE['yourls_username'] ) )
71                 {
72                         yourls_do_action( 'pre_login_cookie' );
73                         $unfiltered_valid = yourls_check_auth_cookie();
74                 }
75         
76         // Regardless of validity, allow plugins to filter the boolean and have final word
77         $valid = yourls_apply_filter( 'is_valid_user', $unfiltered_valid );
78
79         // Login for the win!
80         if ( $valid ) {
81                 yourls_do_action( 'login' );
82                 
83                 // (Re)store encrypted cookie if needed
84                 if ( !yourls_is_API() ) {
85                         yourls_store_cookie( YOURLS_USER );
86                         
87                         // Login form : redirect to requested URL to avoid re-submitting the login form on page reload
88                         if( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) && isset( $_SERVER['REQUEST_URI'] ) ) {
89                                 $url = $_SERVER['REQUEST_URI'];
90                                 yourls_redirect( $url );
91                         }
92                 }
93                 
94                 // Login successful
95                 return true;
96         }
97         
98         // Login failed
99         yourls_do_action( 'login_failed' );
100
101         if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) {
102                 return yourls__( 'Invalid username or password' );
103         } else {
104                 return yourls__( 'Please log in' );
105         }
106 }
107
108 /**
109  * Check auth against list of login=>pwd. Sets user if applicable, returns bool
110  *
111  */
112 function yourls_check_username_password() {
113         global $yourls_user_passwords;
114         if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {
115                 yourls_set_user( $_REQUEST['username'] );
116                 return true;
117         }
118         return false;
119 }
120
121 /**
122  * Check a submitted password sent in plain text against stored password which can be a salted hash
123  *
124  */
125 function yourls_check_password_hash( $user, $submitted_password ) {
126         global $yourls_user_passwords;
127         
128         if( !isset( $yourls_user_passwords[ $user ] ) )
129                 return false;
130         
131         if ( yourls_has_phpass_password( $user ) ) {
132                 // Stored password is hashed with phpass
133                 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] );
134                 $hash = str_replace( '!', '$', $hash );
135                 return ( yourls_phpass_check( $submitted_password, $hash ) );
136         } else if( yourls_has_md5_password( $user ) ) {
137                 // Stored password is a salted md5 hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>"
138                 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] );
139                 return( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
140         } else {
141                 // Password stored in clear text
142                 return( $yourls_user_passwords[ $user ] == $submitted_password );
143         }
144 }
145
146 /**
147  * Overwrite plaintext passwords in config file with phpassed versions.
148  *
149  * @since 1.7
150  * @param string $config_file Full path to file
151  * @return true if overwrite was successful, an error message otherwise
152  */
153 function yourls_hash_passwords_now( $config_file ) {
154         if( !is_readable( $config_file ) )
155                 return 'cannot read file'; // not sure that can actually happen...
156                 
157         if( !is_writable( $config_file ) )
158                 return 'cannot write file';     
159         
160         // Include file to read value of $yourls_user_passwords
161         // Temporary suppress error reporting to avoid notices about redeclared constants
162         $errlevel = error_reporting();
163         error_reporting( 0 );
164         require $config_file;
165         error_reporting( $errlevel );
166         
167         $configdata = file_get_contents( $config_file );
168         if( $configdata == false )
169                 return 'could not read file';
170
171         $to_hash = 0; // keep track of number of passwords that need hashing
172         foreach ( $yourls_user_passwords as $user => $password ) {
173                 if ( !yourls_has_phpass_password( $user ) && !yourls_has_md5_password( $user ) ) {
174                         $to_hash++;
175                         $hash = yourls_phpass_hash( $password );
176                         // PHP would interpret $ as a variable, so replace it in storage.
177                         $hash = str_replace( '$', '!', $hash );
178                         $quotes = "'" . '"';
179                         $pattern = "/[$quotes]${user}[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '-' ) . "[$quotes]/";
180                         $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ ";
181                         $count = 0;
182                         $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
183                         // There should be exactly one replacement. Otherwise, fast fail.
184                         if ( $count != 1 ) {
185                                 global $ydb;
186                                 $ydb->debug_log[] = "Problem with preg_replace for password hash of user $user";
187                                 return 'preg_replace problem';
188                         }
189                 }
190         }
191         
192         if( $to_hash == 0 )
193                 return 0; // There was no password to encrypt
194         
195         $success = file_put_contents( $config_file, $configdata );
196         if ( $success === FALSE ) {
197                 global $ydb;
198                 $ydb->debug_log[] = "Failed writing to " . $config_file;
199                 return 'could not write file';
200         }
201         return true;
202 }
203
204 /**
205  * Hash a password using phpass
206  *
207  * @since 1.7
208  * @param string $password password to hash
209  * @return string hashed password
210  */
211 function yourls_phpass_hash( $password ) {
212         $hasher = yourls_phpass_instance();
213         return $hasher->HashPassword( $password );
214 }
215
216 /**
217  * Check a clear password against a phpass hash
218  *
219  * @since 1.7
220  * @param string $password clear (eg submitted in a form) password
221  * @param string $hash hash supposedly generated by phpass
222  * @return bool true if the hash matches the password once hashed by phpass, false otherwise
223  */
224 function yourls_phpass_check( $password, $hash ) {
225         $hasher = yourls_phpass_instance();
226         return $hasher->CheckPassword( $password, $hash );
227 }
228
229 /**
230  * Helper function: create new instance or return existing instance of phpass class
231  *
232  * @since 1.7
233  * @param int $iteration iteration count - 8 is default in phpass
234  * @param bool $portable flag to force portable (cross platform and system independant) hashes - false to use whatever the system can do best
235  * @return object a PasswordHash instance
236  */
237 function yourls_phpass_instance( $iteration = 8, $portable = false ) {
238         $iteration = yourls_apply_filter( 'phpass_new_instance_iteration', $iteration );
239         $portable  = yourls_apply_filter( 'phpass_new_instance_portable', $portable );
240
241         if( !class_exists( 'PasswordHash' ) ) {
242                 require_once( YOURLS_INC.'/phpass/PasswordHash.php' );
243         }
244
245         static $instance = false;
246         if( $instance == false ) {
247                 $instance = new PasswordHash( $iteration, $portable );
248         }
249         
250         return $instance;
251 }
252
253
254 /**
255  * Check to see if any passwords are stored as cleartext.
256  * 
257  * @since 1.7
258  * @return bool true if any passwords are cleartext
259  */
260 function yourls_has_cleartext_passwords() {
261         global $yourls_user_passwords;
262         foreach ( $yourls_user_passwords as $user => $pwdata ) {
263                 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) {
264                         return true;
265                 }
266         }
267         return false;
268 }
269
270 /**
271  * Check if a user has a hashed password
272  *
273  * Check if a user password is 'md5:[38 chars]'.
274  * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
275  *
276  * @since 1.7
277  * @param string $user user login
278  * @return bool true if password hashed, false otherwise
279  */
280 function yourls_has_md5_password( $user ) {
281         global $yourls_user_passwords;
282         return(    isset( $yourls_user_passwords[ $user ] )
283                 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
284                     && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
285                    );
286 }
287
288 /**
289  * Check if a user's password is hashed with PHPASS.
290  *
291  * Check if a user password is 'phpass:[lots of chars]'.
292  * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
293  *
294  * @since 1.7
295  * @param string $user user login
296  * @return bool true if password hashed with PHPASS, otherwise false
297  */
298 function yourls_has_phpass_password( $user ) {
299         global $yourls_user_passwords;
300         return( isset( $yourls_user_passwords[ $user ] )
301                 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
302         );
303 }
304
305 /**
306  * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
307  *
308  */
309 function yourls_check_auth_cookie() {
310         global $yourls_user_passwords;
311         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
312                 if ( yourls_salt( $valid_user ) == $_COOKIE['yourls_username'] ) {
313                         yourls_set_user( $valid_user );
314                         return true;
315                 }
316         }
317         return false;
318 }
319
320 /**
321  * Check auth against signature and timestamp. Sets user if applicable, returns bool
322  *
323  */
324 function yourls_check_signature_timestamp() {
325         // Timestamp in PHP : time()
326         // Timestamp in JS: parseInt(new Date().getTime() / 1000)
327         global $yourls_user_passwords;
328         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
329                 if (
330                         (
331                                 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
332                                 or
333                                 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
334                         )
335                         &&
336                         yourls_check_timestamp( $_REQUEST['timestamp'] )
337                         ) {
338                         yourls_set_user( $valid_user );
339                         return true;
340                 }
341         }
342         return false;
343 }
344
345 /**
346  * Check auth against signature. Sets user if applicable, returns bool
347  *
348  */
349 function yourls_check_signature() {
350         global $yourls_user_passwords;
351         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
352                 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
353                         yourls_set_user( $valid_user );
354                         return true;
355                 }
356         }
357         return false;
358 }
359
360 /**
361  * Generate secret signature hash
362  *
363  */
364 function yourls_auth_signature( $username = false ) {
365         if( !$username && defined('YOURLS_USER') ) {
366                 $username = YOURLS_USER;
367         }
368         return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
369 }
370
371 /**
372  * Check if timestamp is not too old
373  *
374  */
375 function yourls_check_timestamp( $time ) {
376         $now = time();
377         // Allow timestamp to be a little in the future or the past -- see Issue 766
378         return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
379 }
380
381 /**
382  * Store new cookie. No $user will delete the cookie.
383  *
384  */
385 function yourls_store_cookie( $user = null ) {
386         if( !$user ) {
387                 $pass = null;
388                 $time = time() - 3600;
389         } else {
390                 global $yourls_user_passwords;
391                 if( isset($yourls_user_passwords[$user]) ) {
392                         $pass = $yourls_user_passwords[$user];
393                 } else {
394                         die( 'Stealing cookies?' ); // This should never happen
395                 }
396                 $time = time() + YOURLS_COOKIE_LIFE;
397         }
398         
399         $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( YOURLS_SITE, 1 ) );
400         $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
401         $httponly = yourls_apply_filter( 'setcookie_httponly', true );
402
403         if ( !headers_sent() ) {
404                 // Set httponly if the php version is >= 5.2.0
405                 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
406                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
407                 } else {
408                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure );
409                 }
410         } else {
411                 // For some reason cookies were not stored: action to be able to debug that
412                 yourls_do_action( 'setcookie_failed', $user );
413         }
414 }
415
416 /**
417  * Set user name
418  *
419  */
420 function yourls_set_user( $user ) {
421         if( !defined( 'YOURLS_USER' ) )
422                 define( 'YOURLS_USER', $user );
423 }
424