]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-auth.php
Minor typographical fixes
[Github/YOURLS.git] / includes / functions-auth.php
1 <?php
2 require('PasswordHash.php');
3 /**
4  * Check for valid user via login form or stored cookie. Returns true or an error message
5  *
6  */
7 function yourls_is_valid_user() {
8         static $valid = false;
9         
10         if( $valid )
11                 return true;
12                 
13         // Allow plugins to short-circuit the whole function
14         $pre = yourls_apply_filter( 'shunt_is_valid_user', null );
15         if ( null !== $pre ) {
16                 $valid = ( $pre === true ) ;
17                 return $pre;
18         }
19         
20         // $unfiltered_valid : are credentials valid? Boolean value. It's "unfiltered" to allow plugins to eventually filter it.
21         $unfiltered_valid = false;
22
23         // Logout request
24         if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' ) {
25                 yourls_do_action( 'logout' );
26                 yourls_store_cookie( null );
27                 return yourls__( 'Logged out successfully' );
28         }
29         
30         // Check cookies or login request. Login form has precedence.
31
32         yourls_do_action( 'pre_login' );
33
34         // Determine auth method and check credentials
35         if
36                 // API only: Secure (no login or pwd) and time limited token
37                 // ?timestamp=12345678&signature=md5(totoblah12345678)
38                 ( yourls_is_API() &&
39                   isset( $_REQUEST['timestamp'] ) && !empty($_REQUEST['timestamp'] ) &&
40                   isset( $_REQUEST['signature'] ) && !empty($_REQUEST['signature'] )
41                 )
42                 {
43                         yourls_do_action( 'pre_login_signature_timestamp' );
44                         $unfiltered_valid = yourls_check_signature_timestamp();
45                 }
46                 
47         elseif
48                 // API only: Secure (no login or pwd)
49                 // ?signature=md5(totoblah)
50                 ( yourls_is_API() &&
51                   !isset( $_REQUEST['timestamp'] ) &&
52                   isset( $_REQUEST['signature'] ) && !empty( $_REQUEST['signature'] )
53                 )
54                 {
55                         yourls_do_action( 'pre_login_signature' );
56                         $unfiltered_valid = yourls_check_signature();
57                 }
58         
59         elseif
60                 // API or normal: login with username & pwd
61                 ( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] )
62                   && !empty( $_REQUEST['username'] ) && !empty( $_REQUEST['password']  ) )
63                 {
64                         yourls_do_action( 'pre_login_username_password' );
65                         $unfiltered_valid = yourls_check_username_password();
66                 }
67         
68         elseif
69                 // Normal only: cookies
70                 ( !yourls_is_API() && 
71                   isset( $_COOKIE['yourls_username'] ) )
72                 {
73                         yourls_do_action( 'pre_login_cookie' );
74                         $unfiltered_valid = yourls_check_auth_cookie();
75                 }
76         
77         // Regardless of validity, allow plugins to filter the boolean and have final word
78         $valid = yourls_apply_filter( 'is_valid_user', $unfiltered_valid );
79
80         // Login for the win!
81         if ( $valid ) {
82                 yourls_do_action( 'login' );
83                 
84                 // (Re)store encrypted cookie if needed
85                 if ( !yourls_is_API() ) {
86                         yourls_store_cookie( YOURLS_USER );
87                         
88                         // Login form : redirect to requested URL to avoid re-submitting the login form on page reload
89                         if( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) ) {
90                                 $url = $_SERVER['REQUEST_URI'];
91                                 yourls_redirect( $url );
92                         }
93                 }
94                 
95                 // Login successful
96                 return true;
97         }
98         
99         // Login failed
100         yourls_do_action( 'login_failed' );
101
102         if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) {
103                 return yourls__( 'Invalid username or password' );
104         } else {
105                 return yourls__( 'Please log in' );
106         }
107 }
108
109 /**
110  * Check auth against list of login=>pwd. Sets user if applicable, returns bool
111  *
112  */
113 function yourls_check_username_password() {
114         global $yourls_user_passwords;
115         if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {
116                 yourls_set_user( $_REQUEST['username'] );
117                 return true;
118         }
119         return false;
120 }
121
122 /**
123  * Check a submitted password sent in plain text against stored password which can be a salted hash
124  *
125  */
126 function yourls_check_password_hash( $user, $submitted_password ) {
127         global $yourls_user_passwords;
128         
129         if( !isset( $yourls_user_passwords[ $user ] ) )
130                 return false;
131         
132         if ( yourls_user_has_phppass( $user ) ) {
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_hashed_password( $user ) ) {
138                 // Stored password is a salted 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  * Check if a user's password is hashed with PHPASS.
149  * @since 1.7
150  * @param string $user user login
151  * @return bool true if password hashed with PHPASS, otherwise false
152  */
153 function yourls_user_has_phppass( $user ) {
154         global $yourls_user_passwords;
155         if ( !isset( $yourls_user_passwords[ $user ] ) ) {
156                 return false;
157         }
158
159         $hash = $yourls_user_passwords[ $user ];
160         return ( substr( $hash, 0, 7 ) === 'phpass:' );
161 }
162
163 /**
164  * Overwrite plaintext passwords in config file with hashed versions.
165  * This has the unfortunate side effect of invalidating the session cookie
166  * for any user whose password is changed.
167  * @since 1.7
168  * @return true if overwrite was successful, otherwise false
169  */
170 function yourls_hash_passwords_now() {
171         global $yourls_user_passwords;
172         $hasher = new PasswordHash(8, false);
173         $configdata = file_get_contents( YOURLS_CONFIGFILE );
174         // TODO: check mode for writability
175         foreach ( $yourls_user_passwords as $user => $pwvalue ) {
176                 if ( !yourls_user_has_phppass( $user ) && !yourls_has_hashed_password( $user ) ) {
177                         $clearpass = $pwvalue;
178                         $hash = $hasher->HashPassword( $clearpass );
179                         // PHP would interpret $ as a variable, so replace it in storage.
180                         $hash = str_replace( '$', '!', $hash );
181                         $pattern = "/'$user'[\t ]*=>[\t ]*'$clearpass'/";
182                         $replace = "'$user' => 'phpass:$hash'";
183                         $count = 0;
184                         $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count );
185                         // There should be exactly one replacement. Otherwise, fast fail.
186                         if ( $count != 1 ) {
187                                 error_log( "Problem with preg_replace for password hash of user $user" );
188                                 return false;
189                         }
190                 }
191         }
192         $success = file_put_contents( YOURLS_CONFIGFILE, $configdata );
193         if ( $success === FALSE ) {
194                 error_log( "Failed writing to " . YOURLS_CONFIGFILE );
195                 return false;
196         }
197         return true;
198 }
199
200 /**
201  * Check to see if any passwords are stored as cleartext.
202  * 
203  * @since 1.7
204  * @return bool true if any passwords are cleartext
205  */
206 function yourls_has_cleartext_passwords() {
207         global $yourls_user_passwords;
208         foreach ( $yourls_user_passwords as $user => $pwdata ) {
209                 if ( !yourls_has_hashed_password( $user ) && !yourls_user_has_phppass( $user ) ) {
210                         return true;
211                 }
212         }
213         return false;
214 }
215
216 /**
217  * Check if a user has a hashed password
218  *
219  * Check if a user password is 'md5:[38 chars]'. TODO: deprecate this when/if we have proper user management with
220  * password hashes stored in the DB
221  *
222  * @since 1.7
223  * @param string $user user login
224  * @return bool true if password hashed, false otherwise
225  */
226 function yourls_has_hashed_password( $user ) {
227         global $yourls_user_passwords;
228         return(    isset( $yourls_user_passwords[ $user ] )
229                 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
230                     && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
231                    );
232 }
233
234 /**
235  * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
236  *
237  */
238 function yourls_check_auth_cookie() {
239         global $yourls_user_passwords;
240         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
241                 if ( yourls_salt( $valid_user ) == $_COOKIE['yourls_username'] ) {
242                         yourls_set_user( $valid_user );
243                         return true;
244                 }
245         }
246         return false;
247 }
248
249 /**
250  * Check auth against signature and timestamp. Sets user if applicable, returns bool
251  *
252  */
253 function yourls_check_signature_timestamp() {
254         // Timestamp in PHP : time()
255         // Timestamp in JS: parseInt(new Date().getTime() / 1000)
256         global $yourls_user_passwords;
257         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
258                 if (
259                         (
260                                 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
261                                 or
262                                 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
263                         )
264                         &&
265                         yourls_check_timestamp( $_REQUEST['timestamp'] )
266                         ) {
267                         yourls_set_user( $valid_user );
268                         return true;
269                 }
270         }
271         return false;
272 }
273
274 /**
275  * Check auth against signature. Sets user if applicable, returns bool
276  *
277  */
278 function yourls_check_signature() {
279         global $yourls_user_passwords;
280         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
281                 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
282                         yourls_set_user( $valid_user );
283                         return true;
284                 }
285         }
286         return false;
287 }
288
289 /**
290  * Generate secret signature hash
291  *
292  */
293 function yourls_auth_signature( $username = false ) {
294         if( !$username && defined('YOURLS_USER') ) {
295                 $username = YOURLS_USER;
296         }
297         return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
298 }
299
300 /**
301  * Check if timestamp is not too old
302  *
303  */
304 function yourls_check_timestamp( $time ) {
305         $now = time();
306         // Allow timestamp to be a little in the future or the past -- see Issue 766
307         return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
308 }
309
310 /**
311  * Store new cookie. No $user will delete the cookie.
312  *
313  */
314 function yourls_store_cookie( $user = null ) {
315         if( !$user ) {
316                 $pass = null;
317                 $time = time() - 3600;
318         } else {
319                 global $yourls_user_passwords;
320                 if( isset($yourls_user_passwords[$user]) ) {
321                         $pass = $yourls_user_passwords[$user];
322                 } else {
323                         die( 'Stealing cookies?' ); // This should never happen
324                 }
325                 $time = time() + YOURLS_COOKIE_LIFE;
326         }
327         
328         $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( YOURLS_SITE, 1 ) );
329         $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
330         $httponly = yourls_apply_filter( 'setcookie_httponly', true );
331
332         if ( !headers_sent() ) {
333                 // Set httponly if the php version is >= 5.2.0
334                 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
335                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
336                 } else {
337                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure );
338                 }
339         } else {
340                 // For some reason cookies were not stored: action to be able to debug that
341                 yourls_do_action( 'setcookie_failed', $user );
342         }
343 }
344
345 /**
346  * Set user name
347  *
348  */
349 function yourls_set_user( $user ) {
350         if( !defined( 'YOURLS_USER' ) )
351                 define( 'YOURLS_USER', $user );
352 }
353