]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-auth.php
Be sure to have REQUEST_URI before trying redirection
[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  * @return true if overwrite was successful, an error message otherwise
151  */
152 function yourls_hash_passwords_now() {
153         global $yourls_user_passwords;
154         
155         if( !is_readable( YOURLS_CONFIGFILE ) )
156                 return 'cannot read file'; // not sure that can actually happen...
157                 
158         if( !is_writable( YOURLS_CONFIGFILE ) )
159                 return 'cannot write file';     
160         
161         $configdata = file_get_contents( YOURLS_CONFIGFILE );
162         if( $configdata == false )
163                 return 'could not read file';
164
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 ) ) {
168                         $to_hash++;
169                         $hash = yourls_phpass_hash( $password );
170                         // PHP would interpret $ as a variable, so replace it in storage.
171                         $hash = str_replace( '$', '!', $hash );
172                         $quotes = "'" . '"';
173                         $pattern = "/[$quotes]${user}[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '-' ) . "[$quotes]/";
174                         $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ ";
175                         $count = 0;
176                         $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
177                         // There should be exactly one replacement. Otherwise, fast fail.
178                         if ( $count != 1 ) {
179                                 global $ydb;
180                                 $ydb->debug_log[] = "Problem with preg_replace for password hash of user $user";
181                                 return 'preg_replace problem';
182                         }
183                 }
184         }
185         
186         if( $to_hash == 0 )
187                 return true; // There was no password to encrypt
188         
189         $success = file_put_contents( YOURLS_CONFIGFILE, $configdata );
190         if ( $success === FALSE ) {
191                 global $ydb;
192                 $ydb->debug_log[] = "Failed writing to " . YOURLS_CONFIGFILE;
193                 return 'could not write file';
194         }
195         return true;
196 }
197
198 /**
199  * Hash a password using phpass
200  *
201  * @since 1.7
202  * @param string $password password to hash
203  * @return string hashed password
204  */
205 function yourls_phpass_hash( $password ) {
206         $hasher = yourls_phpass_instance();
207         return $hasher->HashPassword( $password );
208 }
209
210 /**
211  * Check a clear password against a phpass hash
212  *
213  * @since 1.7
214  * @param string $password clear (eg submitted in a form) password
215  * @param string $hash hash supposedly generated by phpass
216  * @return bool true if the hash matches the password once hashed by phpass, false otherwise
217  */
218 function yourls_phpass_check( $password, $hash ) {
219         $hasher = yourls_phpass_instance();
220         return $hasher->CheckPassword( $password, $hash );
221 }
222
223 /**
224  * Helper function: create new instance or return existing instance of phpass class
225  *
226  * @since 1.7
227  * @param int $iteration iteration count - 8 is default in phpass
228  * @param bool $portable flag to force portable (cross platform and system independant) hashes - false to use whatever the system can do best
229  * @return object a PasswordHash instance
230  */
231 function yourls_phpass_instance( $iteration = 8, $portable = false ) {
232         $iteration = yourls_apply_filter( 'phpass_new_instance_iteration', $iteration );
233         $portable  = yourls_apply_filter( 'phpass_new_instance_portable', $portable );
234
235         if( !class_exists( 'PasswordHash' ) ) {
236                 require_once( YOURLS_INC.'/phpass/PasswordHash.php' );
237         }
238
239         static $instance = false;
240         if( $instance == false ) {
241                 $instance = new PasswordHash( $iteration, $portable );
242         }
243         
244         return $instance;
245 }
246
247
248 /**
249  * Check to see if any passwords are stored as cleartext.
250  * 
251  * @since 1.7
252  * @return bool true if any passwords are cleartext
253  */
254 function yourls_has_cleartext_passwords() {
255         global $yourls_user_passwords;
256         foreach ( $yourls_user_passwords as $user => $pwdata ) {
257                 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) {
258                         return true;
259                 }
260         }
261         return false;
262 }
263
264 /**
265  * Check if a user has a hashed password
266  *
267  * Check if a user password is 'md5:[38 chars]'.
268  * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
269  *
270  * @since 1.7
271  * @param string $user user login
272  * @return bool true if password hashed, false otherwise
273  */
274 function yourls_has_md5_password( $user ) {
275         global $yourls_user_passwords;
276         return(    isset( $yourls_user_passwords[ $user ] )
277                 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
278                     && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
279                    );
280 }
281
282 /**
283  * Check if a user's password is hashed with PHPASS.
284  *
285  * Check if a user password is 'phpass:[lots of chars]'.
286  * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
287  *
288  * @since 1.7
289  * @param string $user user login
290  * @return bool true if password hashed with PHPASS, otherwise false
291  */
292 function yourls_has_phpass_password( $user ) {
293         global $yourls_user_passwords;
294         return( isset( $yourls_user_passwords[ $user ] )
295                 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
296         );
297 }
298
299 /**
300  * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
301  *
302  */
303 function yourls_check_auth_cookie() {
304         global $yourls_user_passwords;
305         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
306                 if ( yourls_salt( $valid_user ) == $_COOKIE['yourls_username'] ) {
307                         yourls_set_user( $valid_user );
308                         return true;
309                 }
310         }
311         return false;
312 }
313
314 /**
315  * Check auth against signature and timestamp. Sets user if applicable, returns bool
316  *
317  */
318 function yourls_check_signature_timestamp() {
319         // Timestamp in PHP : time()
320         // Timestamp in JS: parseInt(new Date().getTime() / 1000)
321         global $yourls_user_passwords;
322         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
323                 if (
324                         (
325                                 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
326                                 or
327                                 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
328                         )
329                         &&
330                         yourls_check_timestamp( $_REQUEST['timestamp'] )
331                         ) {
332                         yourls_set_user( $valid_user );
333                         return true;
334                 }
335         }
336         return false;
337 }
338
339 /**
340  * Check auth against signature. Sets user if applicable, returns bool
341  *
342  */
343 function yourls_check_signature() {
344         global $yourls_user_passwords;
345         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
346                 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
347                         yourls_set_user( $valid_user );
348                         return true;
349                 }
350         }
351         return false;
352 }
353
354 /**
355  * Generate secret signature hash
356  *
357  */
358 function yourls_auth_signature( $username = false ) {
359         if( !$username && defined('YOURLS_USER') ) {
360                 $username = YOURLS_USER;
361         }
362         return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
363 }
364
365 /**
366  * Check if timestamp is not too old
367  *
368  */
369 function yourls_check_timestamp( $time ) {
370         $now = time();
371         // Allow timestamp to be a little in the future or the past -- see Issue 766
372         return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
373 }
374
375 /**
376  * Store new cookie. No $user will delete the cookie.
377  *
378  */
379 function yourls_store_cookie( $user = null ) {
380         if( !$user ) {
381                 $pass = null;
382                 $time = time() - 3600;
383         } else {
384                 global $yourls_user_passwords;
385                 if( isset($yourls_user_passwords[$user]) ) {
386                         $pass = $yourls_user_passwords[$user];
387                 } else {
388                         die( 'Stealing cookies?' ); // This should never happen
389                 }
390                 $time = time() + YOURLS_COOKIE_LIFE;
391         }
392         
393         $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( YOURLS_SITE, 1 ) );
394         $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
395         $httponly = yourls_apply_filter( 'setcookie_httponly', true );
396
397         if ( !headers_sent() ) {
398                 // Set httponly if the php version is >= 5.2.0
399                 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
400                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
401                 } else {
402                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure );
403                 }
404         } else {
405                 // For some reason cookies were not stored: action to be able to debug that
406                 yourls_do_action( 'setcookie_failed', $user );
407         }
408 }
409
410 /**
411  * Set user name
412  *
413  */
414 function yourls_set_user( $user ) {
415         if( !defined( 'YOURLS_USER' ) )
416                 define( 'YOURLS_USER', $user );
417 }
418