| [ Index ] |
PHP Cross Reference of YOURLS |
[Summary view] [Print] [Text view]
1 <?php 2 /** 3 * Function related to authentication functions and nonces 4 */ 5 6 7 /** 8 * Show login form if required 9 * 10 * @return void 11 */ 12 function yourls_maybe_require_auth() { 13 if( yourls_is_private() ) { 14 yourls_do_action( 'require_auth' ); 15 require_once ( YOURLS_INC.'/auth.php' ); 16 } else { 17 yourls_do_action( 'require_no_auth' ); 18 } 19 } 20 21 /** 22 * Check for valid user via login form or stored cookie. Returns true or an error message 23 * 24 * @return bool|string|mixed true if valid user, error message otherwise. Can also call yourls_die() or redirect to login page. Oh my. 25 */ 26 function yourls_is_valid_user() { 27 // Allow plugins to short-circuit the whole function 28 $pre = yourls_apply_filter( 'shunt_is_valid_user', yourls_shunt_default() ); 29 if ( yourls_shunt_default() !== $pre ) { 30 return $pre; 31 } 32 33 // $unfiltered_valid : are credentials valid? Boolean value. It's "unfiltered" to allow plugins to eventually filter it. 34 $unfiltered_valid = false; 35 36 // Logout request 37 if( isset( $_GET['action'] ) && $_GET['action'] == 'logout' && isset( $_REQUEST['nonce'] ) ) { 38 // The logout nonce is associated to fake user 'logout' since at this point we don't know the real user 39 yourls_verify_nonce('admin_logout', $_REQUEST['nonce'], 'logout'); 40 yourls_do_action( 'logout' ); 41 yourls_store_cookie( '' ); 42 return yourls__( 'Logged out successfully' ); 43 } 44 45 // Check cookies or login request. Login form has precedence. 46 47 yourls_do_action( 'pre_login' ); 48 49 // Determine auth method and check credentials 50 if 51 // API only: Secure (no login or pwd) and time limited token 52 // ?timestamp=12345678&signature=some-long-sha256-hash 53 ( yourls_is_API() && 54 isset( $_REQUEST['timestamp'] ) && !empty($_REQUEST['timestamp'] ) && 55 isset( $_REQUEST['signature'] ) && !empty($_REQUEST['signature'] ) 56 ) 57 { 58 yourls_do_action( 'pre_login_signature_timestamp' ); 59 $unfiltered_valid = yourls_check_signature_timestamp(); 60 } 61 62 elseif 63 // API only: Secure (no login or pwd) 64 // ?signature=some-long-sha256-hash 65 ( yourls_is_API() && 66 !isset( $_REQUEST['timestamp'] ) && 67 isset( $_REQUEST['signature'] ) && !empty( $_REQUEST['signature'] ) 68 ) 69 { 70 yourls_do_action( 'pre_login_signature' ); 71 $unfiltered_valid = yourls_check_signature(); 72 } 73 74 elseif 75 // API or normal: login with username & pwd 76 ( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) 77 && !empty( $_REQUEST['username'] ) && !empty( $_REQUEST['password'] ) ) 78 { 79 yourls_do_action( 'pre_login_username_password' ); 80 $unfiltered_valid = yourls_check_username_password(); 81 } 82 83 elseif 84 // Normal only: cookies 85 ( !yourls_is_API() && 86 isset( $_COOKIE[ yourls_cookie_name() ] ) ) 87 { 88 yourls_do_action( 'pre_login_cookie' ); 89 $unfiltered_valid = yourls_check_auth_cookie(); 90 } 91 92 // Regardless of validity, allow plugins to filter the boolean and have final word 93 $valid = yourls_apply_filter( 'is_valid_user', $unfiltered_valid ); 94 95 // Login for the win! 96 if ( $valid ) { 97 yourls_do_action( 'login' ); 98 99 // (Re)store encrypted cookie if needed 100 if ( !yourls_is_API() ) { 101 yourls_store_cookie( YOURLS_USER ); 102 103 // Login form : redirect to requested URL to avoid re-submitting the login form on page reload 104 if( isset( $_REQUEST['username'] ) && isset( $_REQUEST['password'] ) && isset( $_SERVER['REQUEST_URI'] ) ) { 105 // The return makes sure we exit this function before waiting for redirection. 106 // See #3189 and note in yourls_redirect() 107 return yourls_redirect( yourls_sanitize_url_safe($_SERVER['REQUEST_URI']) ); 108 } 109 } 110 111 // Login successful 112 return true; 113 } 114 115 // Login failed 116 yourls_do_action( 'login_failed' ); 117 118 if ( isset( $_REQUEST['username'] ) || isset( $_REQUEST['password'] ) ) { 119 return yourls__( 'Invalid username or password' ); 120 } else { 121 return yourls__( 'Please log in' ); 122 } 123 } 124 125 /** 126 * Check auth against list of login=>pwd. Sets user if applicable, returns bool 127 * 128 * @return bool true if login/pwd pair is valid (and sets user if applicable), false otherwise 129 */ 130 function yourls_check_username_password() { 131 global $yourls_user_passwords; 132 133 // If login form (not API), check for nonce 134 if(!yourls_is_API()) { 135 yourls_verify_nonce('admin_login'); 136 } 137 138 if( isset( $yourls_user_passwords[ $_REQUEST['username'] ] ) && yourls_check_password_hash( $_REQUEST['username'], $_REQUEST['password'] ) ) { 139 yourls_set_user( $_REQUEST['username'] ); 140 return true; 141 } 142 return false; 143 } 144 145 /** 146 * Check a submitted password sent in plain text against stored password which can be a salted hash 147 * 148 * @param string $user 149 * @param string $submitted_password 150 * @return bool 151 */ 152 function yourls_check_password_hash($user, $submitted_password ) { 153 global $yourls_user_passwords; 154 155 if( !isset( $yourls_user_passwords[ $user ] ) ) 156 return false; 157 158 if ( yourls_has_phpass_password( $user ) ) { 159 // Stored password is hashed 160 list( , $hash ) = explode( ':', $yourls_user_passwords[ $user ] ); 161 $hash = str_replace( '!', '$', $hash ); 162 return ( yourls_phpass_check( $submitted_password, $hash ) ); 163 } else if( yourls_has_md5_password( $user ) ) { 164 // Stored password is a salted md5 hash: "md5:<$r = rand(10000,99999)>:<md5($r.'thepassword')>" 165 list( , $salt, ) = explode( ':', $yourls_user_passwords[ $user ] ); 166 return hash_equals( $yourls_user_passwords[ $user ], 'md5:'.$salt.':'.md5( $salt . $submitted_password ) ); 167 } else { 168 // Password stored in clear text 169 return hash_equals( (string) $yourls_user_passwords[ $user ], (string) $submitted_password ); 170 } 171 } 172 173 /** 174 * Overwrite plaintext passwords in config file with hashed versions. 175 * 176 * @since 1.7 177 * @param string $config_file Full path to file 178 * @return true|string if overwrite was successful, an error message otherwise 179 */ 180 function yourls_hash_passwords_now( $config_file ) { 181 if( !is_readable( $config_file ) ) { 182 yourls_debug_log( 'Cannot hash passwords: cannot read file ' . $config_file ); 183 return 'cannot read file'; // not sure that can actually happen... 184 } 185 186 if( !is_writable( $config_file ) ) { 187 yourls_debug_log( 'Cannot hash passwords: cannot write file ' . $config_file ); 188 return 'cannot write file'; 189 } 190 191 $yourls_user_passwords = []; 192 // Include file to read value of $yourls_user_passwords 193 // Temporary suppress error reporting to avoid notices about redeclared constants 194 $errlevel = error_reporting(); 195 error_reporting( 0 ); 196 require $config_file; 197 error_reporting( $errlevel ); 198 199 $configdata = file_get_contents( $config_file ); 200 201 if( $configdata == false ) { 202 yourls_debug_log('Cannot hash passwords: file_get_contents() false with ' . $config_file); 203 return 'could not read file'; 204 } 205 206 $to_hash = 0; // keep track of number of passwords that need hashing 207 foreach ( $yourls_user_passwords as $user => $password ) { 208 // avoid "deprecated" warning when password is null -- see test case in tests/data/auth/preg_replace_problem.php 209 $password ??= ''; 210 if ( !yourls_has_phpass_password( $user ) && !yourls_has_md5_password( $user ) ) { 211 $to_hash++; 212 $hash = yourls_phpass_hash( $password ); 213 // PHP would interpret $ as a variable, so replace it in storage. 214 $hash = str_replace( '$', '!', $hash ); 215 $quotes = "'" . '"'; 216 $pattern = "/[$quotes]" . preg_quote( $user, '/' ) . "[$quotes]\s*=>\s*[$quotes]" . preg_quote( $password, '/' ) . "[$quotes]/"; 217 $replace = "'$user' => 'phpass:$hash' /* Password encrypted by YOURLS */ "; 218 $count = 0; 219 $configdata = preg_replace( $pattern, $replace, $configdata, -1, $count ); 220 // There should be exactly one replacement. Otherwise, fast fail. 221 if ( $count != 1 ) { 222 yourls_debug_log( "Problem with preg_replace for password hash of user $user" ); 223 return 'preg_replace problem'; 224 } 225 } 226 } 227 228 if( $to_hash == 0 ) { 229 yourls_debug_log('Cannot hash passwords: no password found in ' . $config_file); 230 return 'no password found'; 231 } 232 233 $success = file_put_contents( $config_file, $configdata ); 234 if ( $success === FALSE ) { 235 yourls_debug_log( 'Failed writing to ' . $config_file ); 236 return 'could not write file'; 237 } 238 239 yourls_debug_log('Successfully encrypted passwords in ' . basename($config_file)); 240 return true; 241 } 242 243 /** 244 * Create a password hash 245 * 246 * @since 1.7 247 * @param string $password password to hash 248 * @return string hashed password 249 */ 250 function yourls_phpass_hash(string $password ): string { 251 /** 252 * Filter for hashing algorithm. See https://www.php.net/manual/en/function.password-hash.php 253 * We're using the default password hashing. This allows us to use better algos as they become 254 * available in future PHP versions, without having to update YOURLS. 255 */ 256 $algo = yourls_apply_filter('hash_algo', PASSWORD_DEFAULT); 257 258 /** 259 * Filter for hashing options. See https://www.php.net/manual/en/function.password-hash.php 260 * A typical option for PASSWORD_BCRYPT would be ['cost' => <int in range 4-31> ] 261 * We're leaving the options at default values, which means a cost of 10 for PASSWORD_BCRYPT. 262 * 263 * If willing to modify this, be warned about the computing time, as there is a 2^n factor. 264 * See https://gist.github.com/ozh/65a75392b7cb254131cc55afd28de99b for examples. 265 */ 266 $options = yourls_apply_filter('hash_options', [] ); 267 268 return password_hash($password, $algo, $options); 269 } 270 271 /** 272 * Verify that a password matches a hash 273 * 274 * @since 1.7 275 * @param string $password clear (eg submitted in a form) password 276 * @param string $hash hash 277 * @return bool true if the hash matches the password, false otherwise 278 */ 279 function yourls_phpass_check( $password, $hash ) { 280 return password_verify($password, $hash); 281 } 282 283 284 /** 285 * Check to see if any passwords are stored as cleartext. 286 * 287 * @since 1.7 288 * @return bool true if any passwords are cleartext 289 */ 290 function yourls_has_cleartext_passwords() { 291 global $yourls_user_passwords; 292 foreach ( $yourls_user_passwords as $user => $pwdata ) { 293 if ( !yourls_has_md5_password( $user ) && !yourls_has_phpass_password( $user ) ) { 294 return true; 295 } 296 } 297 return false; 298 } 299 300 /** 301 * Check to see if any password is stored as md5. 302 * 303 * @since 1.10.5 304 * @return bool true if any passwords are md5 305 */ 306 function yourls_has_md5_passwords(): bool { 307 global $yourls_user_passwords; 308 foreach ( $yourls_user_passwords as $user => $pwdata ) { 309 if ( yourls_has_md5_password($user) ) { 310 return true; 311 } 312 } 313 return false; 314 } 315 316 /** 317 * Check if a user has a md5 hashed password 318 * 319 * Check if a user password is 'md5:[38 chars]'. 320 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB 321 * 322 * @since 1.7 323 * @param string $user user login 324 * @return bool true if password hashed, false otherwise 325 */ 326 function yourls_has_md5_password(string $user ): bool { 327 global $yourls_user_passwords; 328 return( isset( $yourls_user_passwords[ $user ] ) 329 && str_starts_with($yourls_user_passwords[$user], 'md5:') 330 && strlen( $yourls_user_passwords[ $user ] ) == 42 // https://www.google.com/search?q=the+answer+to+life+the+universe+and+everything 331 ); 332 } 333 334 /** 335 * Check if a user's password is hashed with password_hash 336 * 337 * Check if a user password is 'phpass:[lots of chars]'. 338 * (For historical reason we're using 'phpass' as an identifier.) 339 * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB 340 * In such case, check password_needs_rehash() 341 * 342 * @since 1.7 343 * @param string $user user login 344 * @return bool true if password hashed with password_hash, otherwise false 345 */ 346 function yourls_has_phpass_password( $user ) { 347 global $yourls_user_passwords; 348 return( isset( $yourls_user_passwords[ $user ] ) 349 && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:' 350 ); 351 } 352 353 /** 354 * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool 355 * 356 * @return bool true if authenticated, false otherwise 357 */ 358 function yourls_check_auth_cookie() { 359 global $yourls_user_passwords; 360 foreach( $yourls_user_passwords as $valid_user => $valid_password ) { 361 if ( hash_equals( yourls_cookie_value( $valid_user ), (string) $_COOKIE[ yourls_cookie_name() ] ) ) { 362 yourls_set_user( $valid_user ); 363 return true; 364 } 365 } 366 return false; 367 } 368 369 /** 370 * Check auth against signature and timestamp. Sets user if applicable, returns bool 371 * 372 * Original usage : 373 * http://sho.rt/yourls-api.php?timestamp=<timestamp>&signature=<md5 hash>&action=... 374 * Since 1.7.7 we allow a `hash` parameter and an arbitrary hashed signature, hashed 375 * with the `hash` function. Examples : 376 * http://sho.rt/yourls-api.php?timestamp=<timestamp>&signature=<sha512 hash>&hash=sha512&action=... 377 * Since 1.10.5, the hash must be one of: sha256, sha384, or sha512, unless explicitly allowed by a plugin via the 378 * `allowed_hash_algos` filter. 379 * 380 * @see https://yourls.org/docs/guide/advanced/passwordless-api 381 * 382 * @since 1.4.1 383 * @return bool False if signature or timestamp missing or invalid, true if valid 384 */ 385 function yourls_check_signature_timestamp(): bool { 386 if( !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] ) 387 OR !isset( $_REQUEST['timestamp'] ) OR empty( $_REQUEST['timestamp'] ) 388 ) { 389 return false; 390 } 391 392 // Exit if the timestamp argument is outdated or invalid 393 if( !yourls_check_timestamp( $_REQUEST['timestamp'] )) { 394 return false; 395 } 396 397 // if there is a hash argument, make sure it's part of the available and allowed hash algorithms 398 $hash_function = isset($_REQUEST['hash']) ? (string)$_REQUEST['hash'] : yourls_default_hash_algo(); 399 if( !in_array($hash_function, hash_algos()) OR !in_array( $hash_function, yourls_allowed_hash_algos() ) ) { 400 return false; 401 } 402 403 // Check signature & timestamp against all possible users 404 global $yourls_user_passwords; 405 foreach( $yourls_user_passwords as $valid_user => $valid_password ) { 406 if ( 407 hash_equals( hash( $hash_function, $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ), (string) $_REQUEST['signature'] ) 408 or 409 hash_equals( hash( $hash_function, yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ), (string) $_REQUEST['signature'] ) 410 ) { 411 yourls_set_user( $valid_user ); 412 return true; 413 } 414 } 415 416 // Signature doesn't match known user 417 return false; 418 } 419 420 /** 421 * Helper function: return default hash algorithm for signature hashing, which is sha256 unless filtered 422 * 423 * @since 1.10.5 424 * @return string default hash algorithm for signature hashing 425 */ 426 function yourls_default_hash_algo(): string { 427 return yourls_apply_filter('default_hash_algo', 'sha256'); 428 } 429 430 /** 431 * Helper function: return list of allowed hash algorithms for signature hashing, which by default are sha256, sha384, and sha512 unless filtered 432 * 433 * @since 1.10.5 434 * @return array list of allowed hash algorithms for signature hashing 435 */ 436 function yourls_allowed_hash_algos(): array { 437 return yourls_apply_filter( 'allowed_hash_algos', ['sha256', 'sha384', 'sha512'] ); 438 } 439 440 /** 441 * Check auth against signature. Sets user if applicable, returns bool 442 * 443 * @since 1.4.1 444 * @return bool False if signature missing or invalid, true if valid 445 */ 446 function yourls_check_signature() { 447 if( !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] ) ) 448 return false; 449 450 // Check signature against all possible users 451 global $yourls_user_passwords; 452 foreach( $yourls_user_passwords as $valid_user => $valid_password ) { 453 if ( hash_equals( yourls_auth_signature( $valid_user ), (string) $_REQUEST['signature'] ) ) { 454 yourls_set_user( $valid_user ); 455 return true; 456 } 457 } 458 459 // Signature doesn't match known user 460 return false; 461 } 462 463 /** 464 * Generate secret signature hash 465 * 466 * @param false|string $username Username to generate signature for, or false to use current user 467 * @return string Signature 468 */ 469 function yourls_auth_signature(false|string $username = false ): string { 470 if( !$username && defined('YOURLS_USER') ) { 471 $username = YOURLS_USER; 472 } 473 $signature = $username ? substr(yourls_salt('api:' . $username), 0, yourls_auth_signature_length()) : 'Cannot generate auth signature: no username'; 474 475 return yourls_apply_filter( 'auth_signature', $signature, $username ); 476 } 477 478 479 /** 480 * Return length of auth signature, which is 32 chars by default unless filtered 481 * 482 * @return int 483 */ 484 function yourls_auth_signature_length(): int { 485 return (int)yourls_apply_filter( 'auth_signature_length', 32 ); 486 } 487 488 489 /** 490 * Check if timestamp is not too old 491 * 492 * @param int $time Timestamp to check 493 * @return bool True if timestamp is valid 494 */ 495 function yourls_check_timestamp( $time ) { 496 $now = time(); 497 // Allow timestamp to be a little in the future or the past -- see Issue 766 498 return yourls_apply_filter( 'check_timestamp', abs( $now - (int)$time ) < yourls_get_nonce_life(), $time ); 499 } 500 501 /** 502 * Store new cookie. No $user will delete the cookie. 503 * 504 * @param string $user User login, or empty string to delete cookie 505 * @return void 506 */ 507 function yourls_store_cookie(string $user = '' ): void { 508 509 // No user will delete the cookie with a cookie time from the past 510 if( !$user ) { 511 $time = time() - 3600; 512 } else { 513 $time = time() + yourls_get_cookie_life(); 514 } 515 516 $attr = yourls_cookie_attributes(); 517 $path = $attr['path']; 518 $domain = $attr['domain']; 519 $secure = $attr['secure']; 520 $httponly = $attr['httponly']; 521 522 yourls_do_action( 'pre_setcookie', $user, $time, $path, $domain, $secure, $httponly ); 523 524 if ( !headers_sent( $filename, $linenum ) ) { 525 yourls_setcookie( yourls_cookie_name(), yourls_cookie_value( $user ), $time, $path, $domain, $secure, $httponly ); 526 } else { 527 // For some reason cookies were not stored: action to be able to debug that 528 yourls_do_action( 'setcookie_failed', $user ); 529 yourls_debug_log( "Could not store cookie: headers already sent in $filename on line $linenum" ); 530 } 531 } 532 533 /** 534 * Replacement for PHP's setcookie(), with support for SameSite cookie attribute 535 * 536 * @see https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md 537 * @see https://stackoverflow.com/a/59654832/36850 538 * @see https://www.php.net/manual/en/function.setcookie.php 539 * 540 * @since 1.7.7 541 * @param string $name cookie name 542 * @param string $value cookie value 543 * @param int $expire time the cookie expires as a Unix timestamp (number of seconds since the epoch) 544 * @param string $path path on the server in which the cookie will be available on 545 * @param string $domain (sub)domain that the cookie is available to 546 * @param bool $secure if cookie should only be transmitted over a secure HTTPS connection 547 * @param bool $httponly if cookie will be made accessible only through the HTTP protocol 548 * @return bool setcookie() result : false if output sent before, true otherwise. This does not indicate whether the user accepted the cookie. 549 */ 550 function yourls_setcookie($name, $value, $expire, $path, $domain, $secure, $httponly) { 551 $samesite = yourls_apply_filter('setcookie_samesite', 'Lax' ); 552 553 return(setcookie($name, $value, array( 554 'expires' => $expire, 555 'path' => $path, 556 'domain' => $domain, 557 'samesite' => $samesite, 558 'secure' => $secure, 559 'httponly' => $httponly, 560 ))); 561 } 562 563 /** 564 * Get auth cookie attributes after filters 565 * 566 * Single source of truth used both when storing the cookie and when deriving the 567 * cookie name prefix in yourls_cookie_name_prefix(). This guarantees the prefix 568 * matches the attributes actually sent: otherwise the browser silently rejects 569 * the Set-Cookie and breaks login. 570 * 571 * @since 1.10.5 572 * @return array Associative array with keys 'path', 'domain', 'secure', 'httponly' 573 */ 574 function yourls_cookie_attributes(): array { 575 // Cast to string so a null/false return from parse_url normalises to '' and the 576 // __Host- check below stays deterministic 577 $domain = (string) yourls_apply_filter( 'setcookie_domain', parse_url( yourls_get_yourls_site(), PHP_URL_HOST ) ); 578 579 // Some browsers refuse to store localhost cookie 580 if ( $domain === 'localhost' ) { 581 $domain = ''; 582 } 583 584 return array( 585 'path' => yourls_apply_filter( 'setcookie_path', '/' ), 586 'domain' => $domain, 587 'secure' => yourls_apply_filter( 'setcookie_secure', yourls_is_ssl() ), 588 'httponly' => yourls_apply_filter( 'setcookie_httponly', true ), 589 ); 590 } 591 592 /** 593 * Get the cookie name prefix matching the current cookie attributes 594 * 595 * Picks the strongest RFC 6265bis prefix the attributes allow, since both prefixes 596 * are mutually exclusive (a cookie has one name): 597 * __Host- : requires Secure + Path=/ + no Domain attribute (host-only cookie). 598 * On HTTPS, retires the #1673 cross-subdomain concern at the browser 599 * level: the cookie cannot leak to nor be set by sibling subdomains. 600 * __Secure- : requires Secure only. Used when a Domain attribute is set, or when 601 * the cookie path is not '/'. Blocks Set-Cookie from insecure channels. 602 * '' : on HTTP installs, no prefix is possible: the browser would reject 603 * any prefixed cookie that lacks the Secure attribute. 604 * 605 * @since 1.10.5 606 * @return string '__Host-', '__Secure-' or '' depending on cookie attributes 607 */ 608 function yourls_cookie_name_prefix(): string { 609 $attr = yourls_cookie_attributes(); 610 611 // HTTP: browser would reject any prefixed cookie 612 if ( !$attr['secure'] ) { 613 return ''; 614 } 615 // Strongest: host-only at root path 616 if ( $attr['domain'] === '' && $attr['path'] === '/' ) { 617 return '__Host-'; 618 } 619 // Fallback: a Domain is set or path is not '/' 620 return '__Secure-'; 621 } 622 623 /** 624 * Set user name 625 * 626 * @param string $user Username 627 * @return void 628 */ 629 function yourls_set_user( $user ) { 630 if( !defined( 'YOURLS_USER' ) ) 631 define( 'YOURLS_USER', $user ); 632 } 633 634 /** 635 * Get YOURLS_COOKIE_LIFE value (ie the life span of an auth cookie in seconds) 636 * 637 * Use this function instead of directly using the constant. This way, its value can be modified by plugins 638 * on a per case basis. Defaults to 7 days when YOURLS_COOKIE_LIFE is not defined. 639 * 640 * @since 1.7.7 641 * @return integer cookie life span, in seconds 642 */ 643 function yourls_get_cookie_life(): int { 644 $life = defined( 'YOURLS_COOKIE_LIFE' ) ? YOURLS_COOKIE_LIFE : 60 * 60 * 24 * 7; // 7 days 645 return yourls_apply_filter( 'get_cookie_life', $life ); 646 } 647 648 /** 649 * Get YOURLS_NONCE_LIFE value (ie life span of a nonce in seconds) 650 * 651 * Use this function instead of directly using the constant. This way, its value can be modified by plugins 652 * on a per case basis. Defaults to 12 hours when YOURLS_NONCE_LIFE is not defined. 653 * 654 * @since 1.7.7 655 * @see https://en.wikipedia.org/wiki/Cryptographic_nonce 656 * @return integer nonce life span, in seconds 657 */ 658 function yourls_get_nonce_life(): int { 659 $life = defined( 'YOURLS_NONCE_LIFE' ) ? YOURLS_NONCE_LIFE : 60 * 60 * 12; // 12 hours 660 return yourls_apply_filter( 'get_nonce_life', $life ); 661 } 662 663 /** 664 * Get YOURLS cookie name 665 * 666 * The base name is unique per install (salt of the site URL) to prevent collision between eg sho.rt 667 * and very.sho.rt - see #1673. 668 * On HTTPS, the name is additionally prefixed with __Host- or __Secure- to enable browser-side 669 * hardening against cookie injection over insecure channels and, for __Host-, cross-subdomain reads or writes. 670 * See #2785 671 * 672 * TODO: when multi user is implemented, the whole cookie stuff should be reworked to allow storing multiple users 673 * 674 * @since 1.7.1 675 * @return string unique cookie name for a given YOURLS site 676 */ 677 function yourls_cookie_name(): string { 678 $name = yourls_cookie_name_prefix() . 'yourls_' . yourls_salt( yourls_get_yourls_site() ); 679 680 return yourls_apply_filter( 'cookie_name', $name ); 681 } 682 683 /** 684 * Get auth cookie value 685 * 686 * @since 1.7.7 687 * @param string $user user name 688 * @return string cookie value 689 */ 690 function yourls_cookie_value( $user ) { 691 return yourls_apply_filter( 'set_cookie_value', yourls_salt( 'cookie:' . ($user ?? '') ), $user ); 692 } 693 694 /** 695 * Return a time-dependent string for nonce creation 696 * 697 * Actually, this returns a float: ceil rounds up a value but is of type float, see https://www.php.net/ceil 698 * 699 * @return float 700 */ 701 function yourls_tick() { 702 return ceil( time() / yourls_get_nonce_life() ); 703 } 704 705 /** 706 * Get the cookie key (secret used for hashing), as maybe defined in config, filtered 707 * 708 * This is the secret key used by yourls_salt() to hash cookies and nonces. 709 * 710 * @since 1.10.5 711 * @return string Cookie key 712 */ 713 function yourls_get_cookie_key(): string { 714 $key = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : hash('sha256', __FILE__); 715 return yourls_apply_filter( 'get_cookie_key', $key ); 716 } 717 718 /** 719 * Return hashed string 720 * 721 * This function is badly named, it's not a salt or a salted string : it's a cryptographic hash. 722 * 723 * @since 1.4.1 724 * @param string $string string to salt 725 * @return string hashed string 726 */ 727 function yourls_salt(string $string ): string { 728 $salt = yourls_get_cookie_key(); 729 return yourls_apply_filter( 'yourls_salt', hash_hmac( yourls_hmac_algo(), $string, $salt), $string ); 730 } 731 732 /** 733 * Return an available hash_hmac() algorithm 734 * 735 * @since 1.8.3 736 * @return string hash_hmac() algorithm 737 */ 738 function yourls_hmac_algo() { 739 $algo = yourls_apply_filter( 'hmac_algo', 'sha256' ); 740 if( !in_array( $algo, hash_hmac_algos() ) ) { 741 $algo = 'sha256'; 742 } 743 return $algo; 744 } 745 746 /** 747 * Create a time limited, action limited and user limited token 748 * 749 * @param string $action Action to create nonce for 750 * @param false|string $user Optional user string, false for current user 751 * @return string Nonce token 752 */ 753 function yourls_create_nonce($action, $user = false ) { 754 if( false === $user ) { 755 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1'; 756 } 757 $tick = yourls_tick(); 758 $nonce = substr( yourls_salt($tick . $action . $user), 0, 10 ); 759 // Allow plugins to alter the nonce 760 return yourls_apply_filter( 'create_nonce', $nonce, $action, $user ); 761 } 762 763 /** 764 * Echoes or returns a nonce field for inclusion into a form 765 * 766 * @param string $action Action to create nonce for 767 * @param string $name Optional name of nonce field -- defaults to 'nonce' 768 * @param false|string $user Optional user string, false if unspecified 769 * @param bool $echo True to echo, false to return nonce field 770 * @return string Nonce field 771 */ 772 function yourls_nonce_field($action, $name = 'nonce', $user = false, $echo = true ) { 773 $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />'; 774 if( $echo ) 775 echo $field."\n"; 776 return $field; 777 } 778 779 /** 780 * Add a nonce to a URL. If URL omitted, adds nonce to current URL 781 * 782 * @param string $action Action to create nonce for 783 * @param string $url Optional URL to add nonce to -- defaults to current URL 784 * @param string $name Optional name of nonce field -- defaults to 'nonce' 785 * @param false|string $user Optional user string, false if unspecified 786 * @return string URL with nonce added 787 */ 788 function yourls_nonce_url($action, $url = false, $name = 'nonce', $user = false ) { 789 $nonce = yourls_create_nonce( $action, $user ); 790 return yourls_add_query_arg( $name, $nonce, $url ); 791 } 792 793 /** 794 * Check validity of a nonce (ie time span, user and action match). 795 * 796 * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined). 797 * If $nonce is false or unspecified, it will use $_REQUEST['nonce'] 798 * 799 * @param string $action 800 * @param false|string $nonce Optional, string: nonce value, or false to use $_REQUEST['nonce'] 801 * @param false|string $user Optional, string user, false for current user 802 * @param string $return Optional, string: message to die with if nonce is invalid 803 * @return bool|void True if valid, dies otherwise 804 */ 805 function yourls_verify_nonce($action, $nonce = false, $user = false, $return = '' ) { 806 // Get user 807 if( false === $user ) { 808 $user = defined('YOURLS_USER') ? YOURLS_USER : '-1'; 809 } 810 811 // Get nonce value from $_REQUEST if not specified 812 if( false === $nonce && isset( $_REQUEST['nonce'] ) ) { 813 $nonce = $_REQUEST['nonce']; 814 } 815 816 // Allow plugins to short-circuit the rest of the function 817 if (yourls_apply_filter( 'verify_nonce', false, $action, $nonce, $user, $return ) === true) { 818 return true; 819 } 820 821 // What nonce should be 822 $valid = yourls_create_nonce( $action, $user ); 823 824 if( hash_equals( $valid, (string) $nonce ) ) { 825 return true; 826 } else { 827 if( $return ) 828 die( $return ); 829 yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 ); 830 } 831 } 832 833 /** 834 * Check if user credentials comes from environment variables 835 * 836 * @since 1.8.2 837 * @return bool true if credentials are defined as environment variables 838 */ 839 function yourls_is_user_from_env() { 840 return yourls_apply_filter('is_user_from_env', getenv('YOURLS_PASSWORD') || getenv('YOURLS_PASS') || getenv('YOURLS_PASS_FILE')); 841 } 842 843 /** 844 * Check if we should hash passwords in the config file 845 * 846 * By default, passwords are hashed. They are not if 847 * - there is no password in clear text in the config file (ie everything is already hashed) 848 * - the user defined constant YOURLS_NO_HASH_PASSWORD is true, see https://yourls.org/docs/guide/essentials/credentials#i-don-t-want-to-encrypt-my-password 849 * - YOURLS_USER and YOURLS_PASSWORD are provided by the environment, not the config file 850 * 851 * @since 1.8.2 852 * @return bool 853 */ 854 function yourls_maybe_hash_passwords() { 855 $hash = true; 856 857 if ( !yourls_has_cleartext_passwords() 858 OR (yourls_skip_password_hashing()) 859 OR (yourls_is_user_from_env()) 860 ) { 861 $hash = false; 862 } 863 864 return yourls_apply_filter('maybe_hash_password', $hash ); 865 } 866 867 /** 868 * Check if user setting for skipping password hashing is set 869 * 870 * @since 1.8.2 871 * @return bool 872 */ 873 function yourls_skip_password_hashing() { 874 return yourls_apply_filter('skip_password_hashing', defined('YOURLS_NO_HASH_PASSWORD') && YOURLS_NO_HASH_PASSWORD); 875 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body
| Generated: Sun Jul 12 05:10:03 2026 | Cross-referenced by PHPXref 0.7.1 |