]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-auth.php
Fixing and improving stuff on @nicwaller's patch
[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'] ) ) {
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                 $hasher = new PasswordHash( 8, false );
134                 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] );
135                 $hash = str_replace( '!', '$', $hash );
136                 return ( $hasher->CheckPassword( $submitted_password, $hash ) );
137         } else if( yourls_has_md5_password( $user ) ) {
138                 // Stored password is a salted md5 hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>"
139                 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] );
140                 return( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
141         } else {
142                 // Password stored in clear text
143                 return( $yourls_user_passwords[ $user ] == $submitted_password );
144         }
145 }
146
147 /**
148  * Overwrite plaintext passwords in config file with phpassed versions.
149  *
150  * @since 1.7
151  * @return true if overwrite was successful, an error message otherwise
152  */
153 function yourls_hash_passwords_now() {
154         global $yourls_user_passwords;
155         
156         $configdata = file_get_contents( YOURLS_CONFIGFILE );
157         if( $configdata == false )
158                 return 'could not read file';
159
160         $to_hash = 0; // keep track of number of passwords that need hashing
161         $hasher  = new PasswordHash( 8, false );
162         
163         // TODO: check mode for writability
164         foreach ( $yourls_user_passwords as $user => $password ) {
165                 if ( !yourls_has_phpass_password( $user ) && !yourls_has_md5_password( $user ) ) {
166                         $to_hash++;
167                         $hash = $hasher->HashPassword( $password );
168                         // PHP would interpret $ as a variable, so replace it in storage.
169                         $hash = str_replace( '$', '!', $hash );
170                         $quotes = "'" . '"';
171                         $pattern = "/[$quotes]${user}[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '-' ) . "[$quotes]/";
172                         $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ ";
173                         $count = 0;
174                         $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
175                         // There should be exactly one replacement. Otherwise, fast fail.
176                         if ( $count != 1 ) {
177                                 global $ydb;
178                                 $ydb->debug_log[] = "Problem with preg_replace for password hash of user $user";
179                                 return 'preg_replace problem';
180                         }
181                 }
182         }
183         
184         if( $to_hash == 0 )
185                 return true; // There was no password to encrypt
186         
187         $success = file_put_contents( YOURLS_CONFIGFILE, $configdata );
188         if ( $success === FALSE ) {
189                 global $ydb;
190                 $ydb->debug_log[] = "Failed writing to " . YOURLS_CONFIGFILE;
191                 return 'could not write file';
192         }
193         return true;
194 }
195
196 /**
197  * Check to see if any passwords are stored as cleartext.
198  * 
199  * @since 1.7
200  * @return bool true if any passwords are cleartext
201  */
202 function yourls_has_cleartext_passwords() {
203         global $yourls_user_passwords;
204         foreach ( $yourls_user_passwords as $user => $pwdata ) {
205                 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) {
206                         return true;
207                 }
208         }
209         return false;
210 }
211
212 /**
213  * Check if a user has a hashed password
214  *
215  * Check if a user password is 'md5:[38 chars]'. TODO: deprecate this when/if we have proper user management with
216  * password hashes stored in the DB
217  *
218  * @since 1.7
219  * @param string $user user login
220  * @return bool true if password hashed, false otherwise
221  */
222 function yourls_has_md5_password( $user ) {
223         global $yourls_user_passwords;
224         return(    isset( $yourls_user_passwords[ $user ] )
225                 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
226                     && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
227                    );
228 }
229
230 /**
231  * Check if a user's password is hashed with PHPASS.
232  *
233  * @since 1.7
234  * @param string $user user login
235  * @return bool true if password hashed with PHPASS, otherwise false
236  */
237 function yourls_has_phpass_password( $user ) {
238         global $yourls_user_passwords;
239         return( isset( $yourls_user_passwords[ $user ] )
240                 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
241         );
242 }
243
244 /**
245  * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
246  *
247  */
248 function yourls_check_auth_cookie() {
249         global $yourls_user_passwords;
250         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
251                 if ( yourls_salt( $valid_user ) == $_COOKIE['yourls_username'] ) {
252                         yourls_set_user( $valid_user );
253                         return true;
254                 }
255         }
256         return false;
257 }
258
259 /**
260  * Check auth against signature and timestamp. Sets user if applicable, returns bool
261  *
262  */
263 function yourls_check_signature_timestamp() {
264         // Timestamp in PHP : time()
265         // Timestamp in JS: parseInt(new Date().getTime() / 1000)
266         global $yourls_user_passwords;
267         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
268                 if (
269                         (
270                                 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
271                                 or
272                                 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
273                         )
274                         &&
275                         yourls_check_timestamp( $_REQUEST['timestamp'] )
276                         ) {
277                         yourls_set_user( $valid_user );
278                         return true;
279                 }
280         }
281         return false;
282 }
283
284 /**
285  * Check auth against signature. Sets user if applicable, returns bool
286  *
287  */
288 function yourls_check_signature() {
289         global $yourls_user_passwords;
290         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
291                 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
292                         yourls_set_user( $valid_user );
293                         return true;
294                 }
295         }
296         return false;
297 }
298
299 /**
300  * Generate secret signature hash
301  *
302  */
303 function yourls_auth_signature( $username = false ) {
304         if( !$username && defined('YOURLS_USER') ) {
305                 $username = YOURLS_USER;
306         }
307         return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
308 }
309
310 /**
311  * Check if timestamp is not too old
312  *
313  */
314 function yourls_check_timestamp( $time ) {
315         $now = time();
316         // Allow timestamp to be a little in the future or the past -- see Issue 766
317         return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
318 }
319
320 /**
321  * Store new cookie. No $user will delete the cookie.
322  *
323  */
324 function yourls_store_cookie( $user = null ) {
325         if( !$user ) {
326                 $pass = null;
327                 $time = time() - 3600;
328         } else {
329                 global $yourls_user_passwords;
330                 if( isset($yourls_user_passwords[$user]) ) {
331                         $pass = $yourls_user_passwords[$user];
332                 } else {
333                         die( 'Stealing cookies?' ); // This should never happen
334                 }
335                 $time = time() + YOURLS_COOKIE_LIFE;
336         }
337         
338         $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( YOURLS_SITE, 1 ) );
339         $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
340         $httponly = yourls_apply_filter( 'setcookie_httponly', true );
341
342         if ( !headers_sent() ) {
343                 // Set httponly if the php version is >= 5.2.0
344                 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
345                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
346                 } else {
347                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure );
348                 }
349         } else {
350                 // For some reason cookies were not stored: action to be able to debug that
351                 yourls_do_action( 'setcookie_failed', $user );
352         }
353 }
354
355 /**
356  * Set user name
357  *
358  */
359 function yourls_set_user( $user ) {
360         if( !defined( 'YOURLS_USER' ) )
361                 define( 'YOURLS_USER', $user );
362 }
363