]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-auth.php
More secure password hashes with PHPASS
[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'] ) && isset( $_COOKIE['yourls_password'] ) )
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                                 // If password stored unencrypted, append query string. TODO: deprecate this when there's proper user management
92                                 if( !yourls_has_hashed_password( $_REQUEST['username'] ) ) {
93                                         $url = yourls_add_query_arg( array( 'login_msg' => 'pwdclear' ) );
94                                 }
95                                 yourls_redirect( $url );
96                         }
97                 }
98                 
99                 // Login successful
100                 return true;
101         }
102         
103         // Login failed
104         yourls_do_action( 'login_failed' );
105
106         if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) {
107                 return yourls__( 'Invalid username or password' );
108         } else {
109                 return yourls__( 'Please log in' );
110         }
111 }
112
113 /**
114  * Check auth against list of login=>pwd. Sets user if applicable, returns bool
115  *
116  */
117 function yourls_check_username_password() {
118         global $yourls_user_passwords;
119         if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) {
120                 yourls_set_user( $_REQUEST['username'] );
121                 return true;
122         }
123         return false;
124 }
125
126 /**
127  * Check a submitted password sent in plain text against stored password which can be a salted hash
128  *
129  */
130 function yourls_check_password_hash( $user, $submitted_password ) {
131         global $yourls_user_passwords;
132         
133         if( !isset( $yourls_user_passwords[ $user ] ) )
134                 return false;
135         
136         if ( yourls_user_has_phppass( $user ) ) {
137                 $hasher = new PasswordHash(8, false);
138                 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] );
139                 return ( $hasher->CheckPassword( $submitted_password, $hash ) );
140         } else if( yourls_has_hashed_password( $user ) ) {
141                 // Stored password is a salted hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>"
142                 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] );
143                 return( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
144         } else {
145                 // Password stored in clear text
146                 return( $yourls_user_passwords[ $user ] == $submitted_password );
147         }
148 }
149
150 /**
151  * Check if a user's password is hashed with PHPASS.
152  * @since 1.7
153  * @param string $user user login
154  * @return bool true if password hashed with PHPASS, otherwise false
155  */
156 function yourls_user_has_phppass( $user ) {
157         global $yourls_user_passwords;
158         if ( !isset( $yourls_user_passwords[ $user ] ) ) {
159                 return false;
160         }
161
162         $hash = $yourls_user_passwords[ $user ];
163         return ( substr( $hash, 0, 7 ) === 'phpass:' );
164 }
165
166 /**
167  * Overwrite plaintext passwords in config file with hashed versions.
168  * @since 1.7
169  * @return true if overwrite was successful, otherwise false
170  */
171 function yourls_hash_passwords_now() {
172         global $yourls_user_passwords;
173         $hasher = new PasswordHash(8, false);
174         foreach ( $yourls_user_passwords as $user => $pwvalue ) {
175                 if ( !yourls_user_has_phppass( $user ) && !yourls_has_hashed_password( $user ) ) {
176                         $clearpass = $pwvalue;
177                         $hash = $hasher->HashPassword($clearpass);
178                         // TODO: use sed/awk to rewrite entry in config file, carefully!
179                         // something like this
180                         // sed -i "s/'root' *=> *'1234234134'/'root' => '123412341241234'/" config.php
181                 }
182         }
183 }
184
185 /**
186  * Check if a user has a hashed password
187  *
188  * Check if a user password is 'md5:[38 chars]'. TODO: deprecate this when/if we have proper user management with
189  * password hashes stored in the DB
190  *
191  * @since 1.7
192  * @param string $user user login
193  * @return bool true if password hashed, false otherwise
194  */
195 function yourls_has_hashed_password( $user ) {
196         global $yourls_user_passwords;
197         return(    isset( $yourls_user_passwords[ $user ] )
198                 && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
199                     && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
200                    );
201 }
202
203 /**
204  * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
205  *
206  */
207 function yourls_check_auth_cookie() {
208         global $yourls_user_passwords;
209         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
210                 if( 
211                         yourls_salt( $valid_user ) == $_COOKIE['yourls_username']
212                         && yourls_salt( $valid_password ) == $_COOKIE['yourls_password'] 
213                 ) {
214                         yourls_set_user( $valid_user );
215                         return true;
216                 }
217         }
218         return false;
219 }
220
221 /**
222  * Check auth against signature and timestamp. Sets user if applicable, returns bool
223  *
224  */
225 function yourls_check_signature_timestamp() {
226         // Timestamp in PHP : time()
227         // Timestamp in JS: parseInt(new Date().getTime() / 1000)
228         global $yourls_user_passwords;
229         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
230                 if (
231                         (
232                                 md5( $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) == $_REQUEST['signature']
233                                 or
234                                 md5( yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) == $_REQUEST['signature']
235                         )
236                         &&
237                         yourls_check_timestamp( $_REQUEST['timestamp'] )
238                         ) {
239                         yourls_set_user( $valid_user );
240                         return true;
241                 }
242         }
243         return false;
244 }
245
246 /**
247  * Check auth against signature. Sets user if applicable, returns bool
248  *
249  */
250 function yourls_check_signature() {
251         global $yourls_user_passwords;
252         foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
253                 if ( yourls_auth_signature( $valid_user ) == $_REQUEST['signature'] ) {
254                         yourls_set_user( $valid_user );
255                         return true;
256                 }
257         }
258         return false;
259 }
260
261 /**
262  * Generate secret signature hash
263  *
264  */
265 function yourls_auth_signature( $username = false ) {
266         if( !$username && defined('YOURLS_USER') ) {
267                 $username = YOURLS_USER;
268         }
269         return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
270 }
271
272 /**
273  * Check if timestamp is not too old
274  *
275  */
276 function yourls_check_timestamp( $time ) {
277         $now = time();
278         // Allow timestamp to be a little in the future or the past -- see Issue 766
279         return yourls_apply_filter( 'check_timestamp', abs( $now - $time ) < YOURLS_NONCE_LIFE, $time );
280 }
281
282 /**
283  * Store new cookie. No $user will delete the cookie.
284  *
285  */
286 function yourls_store_cookie( $user = null ) {
287         if( !$user ) {
288                 $pass = null;
289                 $time = time() - 3600;
290         } else {
291                 global $yourls_user_passwords;
292                 if( isset($yourls_user_passwords[$user]) ) {
293                         $pass = $yourls_user_passwords[$user];
294                 } else {
295                         die( 'Stealing cookies?' ); // This should never happen
296                 }
297                 $time = time() + YOURLS_COOKIE_LIFE;
298         }
299         
300         $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( YOURLS_SITE, 1 ) );
301         $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
302         $httponly = yourls_apply_filter( 'setcookie_httponly', true );
303                 
304         if ( !headers_sent() ) {
305                 // Set httponly if the php version is >= 5.2.0
306                 if( version_compare( phpversion(), '5.2.0', 'ge' ) ) {
307                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure, $httponly );
308                         setcookie('yourls_password', yourls_salt( $pass ), $time, '/', $domain, $secure, $httponly );
309                 } else {
310                         setcookie('yourls_username', yourls_salt( $user ), $time, '/', $domain, $secure );
311                         setcookie('yourls_password', yourls_salt( $pass ), $time, '/', $domain, $secure );
312                 }
313         } else {
314                 // For some reason cookies were not stored: action to be able to debug that
315                 yourls_do_action( 'setcookie_failed', $user );
316         }
317 }
318
319 /**
320  * Set user name
321  *
322  */
323 function yourls_set_user( $user ) {
324         if( !defined( 'YOURLS_USER' ) )
325                 define( 'YOURLS_USER', $user );
326 }
327