[ Index ]

PHP Cross Reference of YOURLS

title

Body

[close]

/includes/ -> functions-auth.php (source)

   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', null );
  29      if ( null !== $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=md5(totoblah12345678)
  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=md5(totoblah)
  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( $yourls_user_passwords[ $user ] == 'md5:'.$salt.':'.md5( $salt . $submitted_password ) );
 167      } else {
 168          // Password stored in clear text
 169          return( $yourls_user_passwords[ $user ] === $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]$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( $password ) {
 251      /**
 252       * Filter for hashing algorithm. See https://www.php.net/manual/en/function.password-hash.php
 253       * Hashing algos are available if PHP was compiled with it.
 254       * PASSWORD_BCRYPT is always available.
 255       */
 256      $algo    = yourls_apply_filter('hash_algo', PASSWORD_BCRYPT);
 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 if a user has a md5 hashed password
 302   *
 303   * Check if a user password is 'md5:[38 chars]'.
 304   * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
 305   *
 306   * @since 1.7
 307   * @param string $user user login
 308   * @return bool true if password hashed, false otherwise
 309   */
 310  function yourls_has_md5_password( $user ) {
 311      global $yourls_user_passwords;
 312      return(    isset( $yourls_user_passwords[ $user ] )
 313              && substr( $yourls_user_passwords[ $user ], 0, 4 ) == 'md5:'
 314              && strlen( $yourls_user_passwords[ $user ] ) == 42 // http://www.google.com/search?q=the+answer+to+life+the+universe+and+everything
 315             );
 316  }
 317  
 318  /**
 319   * Check if a user's password is hashed with password_hash
 320   *
 321   * Check if a user password is 'phpass:[lots of chars]'.
 322   * (For historical reason we're using 'phpass' as an identifier.)
 323   * TODO: deprecate this when/if we have proper user management with password hashes stored in the DB
 324   *
 325   * @since 1.7
 326   * @param string $user user login
 327   * @return bool true if password hashed with password_hash, otherwise false
 328   */
 329  function yourls_has_phpass_password( $user ) {
 330      global $yourls_user_passwords;
 331      return( isset( $yourls_user_passwords[ $user ] )
 332              && substr( $yourls_user_passwords[ $user ], 0, 7 ) == 'phpass:'
 333      );
 334  }
 335  
 336  /**
 337   * Check auth against encrypted COOKIE data. Sets user if applicable, returns bool
 338   *
 339   * @return bool true if authenticated, false otherwise
 340   */
 341  function yourls_check_auth_cookie() {
 342      global $yourls_user_passwords;
 343      foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
 344          if ( yourls_cookie_value( $valid_user ) === $_COOKIE[ yourls_cookie_name() ] ) {
 345              yourls_set_user( $valid_user );
 346              return true;
 347          }
 348      }
 349      return false;
 350  }
 351  
 352  /**
 353   * Check auth against signature and timestamp. Sets user if applicable, returns bool
 354   *
 355   * Original usage :
 356   *   http://sho.rt/yourls-api.php?timestamp=<timestamp>&signature=<md5 hash>&action=...
 357   * Since 1.7.7 we allow a `hash` parameter and an arbitrary hashed signature, hashed
 358   * with the `hash` function. Examples :
 359   *   http://sho.rt/yourls-api.php?timestamp=<timestamp>&signature=<sha512 hash>&hash=sha512&action=...
 360   *   http://sho.rt/yourls-api.php?timestamp=<timestamp>&signature=<crc32 hash>&hash=crc32&action=...
 361   *
 362   * @since 1.4.1
 363   * @return bool False if signature or timestamp missing or invalid, true if valid
 364   */
 365  function yourls_check_signature_timestamp() {
 366      if(   !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] )
 367         OR !isset( $_REQUEST['timestamp'] ) OR empty( $_REQUEST['timestamp'] )
 368      ) {
 369          return false;
 370      }
 371  
 372      // Exit if the timestamp argument is outdated or invalid
 373      if( !yourls_check_timestamp( $_REQUEST['timestamp'] )) {
 374          return false;
 375      }
 376  
 377      // if there is a hash argument, make sure it's part of the availables algos
 378      $hash_function = isset($_REQUEST['hash']) ? (string)$_REQUEST['hash'] : 'md5';
 379      if( !in_array($hash_function, hash_algos()) ) {
 380          return false;
 381      }
 382  
 383      // Check signature & timestamp against all possible users
 384      global $yourls_user_passwords;
 385      foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
 386          if (
 387              hash( $hash_function, $_REQUEST['timestamp'].yourls_auth_signature( $valid_user ) ) === $_REQUEST['signature']
 388              or
 389              hash( $hash_function, yourls_auth_signature( $valid_user ).$_REQUEST['timestamp'] ) === $_REQUEST['signature']
 390              ) {
 391              yourls_set_user( $valid_user );
 392              return true;
 393          }
 394      }
 395  
 396      // Signature doesn't match known user
 397      return false;
 398  }
 399  
 400  /**
 401   * Check auth against signature. Sets user if applicable, returns bool
 402   *
 403   * @since 1.4.1
 404   * @return bool False if signature missing or invalid, true if valid
 405   */
 406  function yourls_check_signature() {
 407      if( !isset( $_REQUEST['signature'] ) OR empty( $_REQUEST['signature'] ) )
 408          return false;
 409  
 410      // Check signature against all possible users
 411      global $yourls_user_passwords;
 412      foreach( $yourls_user_passwords as $valid_user => $valid_password ) {
 413          if ( yourls_auth_signature( $valid_user ) === $_REQUEST['signature'] ) {
 414              yourls_set_user( $valid_user );
 415              return true;
 416          }
 417      }
 418  
 419      // Signature doesn't match known user
 420      return false;
 421  }
 422  
 423  /**
 424   * Generate secret signature hash
 425   *
 426   * @param false|string $username  Username to generate signature for, or false to use current user
 427   * @return string                 Signature
 428   */
 429  function yourls_auth_signature( $username = false ) {
 430      if( !$username && defined('YOURLS_USER') ) {
 431          $username = YOURLS_USER;
 432      }
 433      return ( $username ? substr( yourls_salt( $username ), 0, 10 ) : 'Cannot generate auth signature: no username' );
 434  }
 435  
 436  /**
 437   * Check if timestamp is not too old
 438   *
 439   * @param int $time  Timestamp to check
 440   * @return bool      True if timestamp is valid
 441   */
 442  function yourls_check_timestamp( $time ) {
 443      $now = time();
 444      // Allow timestamp to be a little in the future or the past -- see Issue 766
 445      return yourls_apply_filter( 'check_timestamp', abs( $now - (int)$time ) < yourls_get_nonce_life(), $time );
 446  }
 447  
 448  /**
 449   * Store new cookie. No $user will delete the cookie.
 450   *
 451   * @param string $user  User login, or empty string to delete cookie
 452   * @return void
 453   */
 454  function yourls_store_cookie( $user = '' ) {
 455  
 456      // No user will delete the cookie with a cookie time from the past
 457      if( !$user ) {
 458          $time = time() - 3600;
 459      } else {
 460          $time = time() + yourls_get_cookie_life();
 461      }
 462  
 463      $path     = yourls_apply_filter( 'setcookie_path',     '/' );
 464      $domain   = yourls_apply_filter( 'setcookie_domain',   parse_url( yourls_get_yourls_site(), PHP_URL_HOST ) );
 465      $secure   = yourls_apply_filter( 'setcookie_secure',   yourls_is_ssl() );
 466      $httponly = yourls_apply_filter( 'setcookie_httponly', true );
 467  
 468      // Some browsers refuse to store localhost cookie
 469      if ( $domain == 'localhost' )
 470          $domain = '';
 471  
 472      yourls_do_action( 'pre_setcookie', $user, $time, $path, $domain, $secure, $httponly );
 473  
 474      if ( !headers_sent( $filename, $linenum ) ) {
 475          yourls_setcookie( yourls_cookie_name(), yourls_cookie_value( $user ), $time, $path, $domain, $secure, $httponly );
 476      } else {
 477          // For some reason cookies were not stored: action to be able to debug that
 478          yourls_do_action( 'setcookie_failed', $user );
 479          yourls_debug_log( "Could not store cookie: headers already sent in $filename on line $linenum" );
 480      }
 481  }
 482  
 483  /**
 484   * Replacement for PHP's setcookie(), with support for SameSite cookie attribute
 485   *
 486   * @see https://github.com/GoogleChromeLabs/samesite-examples/blob/master/php.md
 487   * @see https://stackoverflow.com/a/59654832/36850
 488   * @see https://www.php.net/manual/en/function.setcookie.php
 489   *
 490   * @since  1.7.7
 491   * @param  string  $name       cookie name
 492   * @param  string  $value      cookie value
 493   * @param  int     $expire     time the cookie expires as a Unix timestamp (number of seconds since the epoch)
 494   * @param  string  $path       path on the server in which the cookie will be available on
 495   * @param  string  $domain     (sub)domain that the cookie is available to
 496   * @param  bool    $secure     if cookie should only be transmitted over a secure HTTPS connection
 497   * @param  bool    $httponly   if cookie will be made accessible only through the HTTP protocol
 498   * @return bool                setcookie() result : false if output sent before, true otherwise. This does not indicate whether the user accepted the cookie.
 499   */
 500  function yourls_setcookie($name, $value, $expire, $path, $domain, $secure, $httponly) {
 501      $samesite = yourls_apply_filter('setcookie_samesite', 'Lax' );
 502  
 503      return(setcookie($name, $value, array(
 504          'expires'  => $expire,
 505          'path'     => $path,
 506          'domain'   => $domain,
 507          'samesite' => $samesite,
 508          'secure'   => $secure,
 509          'httponly' => $httponly,
 510      )));
 511  }
 512  
 513  /**
 514   * Set user name
 515   *
 516   * @param string $user  Username
 517   * @return void
 518   */
 519  function yourls_set_user( $user ) {
 520      if( !defined( 'YOURLS_USER' ) )
 521          define( 'YOURLS_USER', $user );
 522  }
 523  
 524  /**
 525   * Get YOURLS_COOKIE_LIFE value (ie the life span of an auth cookie in seconds)
 526   *
 527   * Use this function instead of directly using the constant. This way, its value can be modified by plugins
 528   * on a per case basis
 529   *
 530   * @since 1.7.7
 531   * @see includes/Config/Config.php
 532   * @return integer     cookie life span, in seconds
 533   */
 534  function yourls_get_cookie_life() {
 535      return yourls_apply_filter( 'get_cookie_life', YOURLS_COOKIE_LIFE );
 536  }
 537  
 538  /**
 539   * Get YOURLS_NONCE_LIFE value (ie life span of a nonce in seconds)
 540   *
 541   * Use this function instead of directly using the constant. This way, its value can be modified by plugins
 542   * on a per case basis
 543   *
 544   * @since 1.7.7
 545   * @see includes/Config/Config.php
 546   * @see https://en.wikipedia.org/wiki/Cryptographic_nonce
 547   * @return integer     nonce life span, in seconds
 548   */
 549  function yourls_get_nonce_life() {
 550      return yourls_apply_filter( 'get_nonce_life', YOURLS_NONCE_LIFE );
 551  }
 552  
 553  /**
 554   * Get YOURLS cookie name
 555   *
 556   * The name is unique for each install, to prevent mismatch between sho.rt and very.sho.rt -- see #1673
 557   *
 558   * TODO: when multi user is implemented, the whole cookie stuff should be reworked to allow storing multiple users
 559   *
 560   * @since 1.7.1
 561   * @return string  unique cookie name for a given YOURLS site
 562   */
 563  function yourls_cookie_name() {
 564      return yourls_apply_filter( 'cookie_name', 'yourls_' . yourls_salt( yourls_get_yourls_site() ) );
 565  }
 566  
 567  /**
 568   * Get auth cookie value
 569   *
 570   * @since 1.7.7
 571   * @param string $user     user name
 572   * @return string          cookie value
 573   */
 574  function yourls_cookie_value( $user ) {
 575      return yourls_apply_filter( 'set_cookie_value', yourls_salt( $user ?? '' ), $user );
 576  }
 577  
 578  /**
 579   * Return a time-dependent string for nonce creation
 580   *
 581   * Actually, this returns a float: ceil rounds up a value but is of type float, see https://www.php.net/ceil
 582   *
 583   * @return float
 584   */
 585  function yourls_tick() {
 586      return ceil( time() / yourls_get_nonce_life() );
 587  }
 588  
 589  /**
 590   * Return hashed string
 591   *
 592   * This function is badly named, it's not a salt or a salted string : it's a cryptographic hash.
 593   *
 594   * @since 1.4.1
 595   * @param string $string   string to salt
 596   * @return string          hashed string
 597   */
 598  function yourls_salt( $string ) {
 599      $salt = defined('YOURLS_COOKIEKEY') ? YOURLS_COOKIEKEY : md5(__FILE__) ;
 600      return yourls_apply_filter( 'yourls_salt', hash_hmac( yourls_hmac_algo(), $string,  $salt), $string );
 601  }
 602  
 603  /**
 604   * Return an available hash_hmac() algorithm
 605   *
 606   * @since 1.8.3
 607   * @return string  hash_hmac() algorithm
 608   */
 609  function yourls_hmac_algo() {
 610      $algo = yourls_apply_filter( 'hmac_algo', 'sha256' );
 611      if( !in_array( $algo, hash_hmac_algos() ) ) {
 612          $algo = 'sha256';
 613      }
 614      return $algo;
 615  }
 616  
 617  /**
 618   * Create a time limited, action limited and user limited token
 619   *
 620   * @param string $action      Action to create nonce for
 621   * @param false|string $user  Optional user string, false for current user
 622   * @return string             Nonce token
 623   */
 624  function yourls_create_nonce($action, $user = false ) {
 625      if( false === $user ) {
 626          $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
 627      }
 628      $tick = yourls_tick();
 629      $nonce = substr( yourls_salt($tick . $action . $user), 0, 10 );
 630      // Allow plugins to alter the nonce
 631      return yourls_apply_filter( 'create_nonce', $nonce, $action, $user );
 632  }
 633  
 634  /**
 635   * Echoes or returns a nonce field for inclusion into a form
 636   *
 637   * @param string $action      Action to create nonce for
 638   * @param string $name        Optional name of nonce field -- defaults to 'nonce'
 639   * @param false|string $user  Optional user string, false if unspecified
 640   * @param bool $echo          True to echo, false to return nonce field
 641   * @return string             Nonce field
 642   */
 643  function yourls_nonce_field($action, $name = 'nonce', $user = false, $echo = true ) {
 644      $field = '<input type="hidden" id="'.$name.'" name="'.$name.'" value="'.yourls_create_nonce( $action, $user ).'" />';
 645      if( $echo )
 646          echo $field."\n";
 647      return $field;
 648  }
 649  
 650  /**
 651   * Add a nonce to a URL. If URL omitted, adds nonce to current URL
 652   *
 653   * @param string $action      Action to create nonce for
 654   * @param string $url         Optional URL to add nonce to -- defaults to current URL
 655   * @param string $name        Optional name of nonce field -- defaults to 'nonce'
 656   * @param false|string $user  Optional user string, false if unspecified
 657   * @return string             URL with nonce added
 658   */
 659  function yourls_nonce_url($action, $url = false, $name = 'nonce', $user = false ) {
 660      $nonce = yourls_create_nonce( $action, $user );
 661      return yourls_add_query_arg( $name, $nonce, $url );
 662  }
 663  
 664  /**
 665   * Check validity of a nonce (ie time span, user and action match).
 666   *
 667   * Returns true if valid, dies otherwise (yourls_die() or die($return) if defined).
 668   * If $nonce is false or unspecified, it will use $_REQUEST['nonce']
 669   *
 670   * @param string $action
 671   * @param false|string $nonce  Optional, string: nonce value, or false to use $_REQUEST['nonce']
 672   * @param false|string $user   Optional, string user, false for current user
 673   * @param string $return       Optional, string: message to die with if nonce is invalid
 674   * @return bool|void           True if valid, dies otherwise
 675   */
 676  function yourls_verify_nonce($action, $nonce = false, $user = false, $return = '' ) {
 677      // Get user
 678      if( false === $user ) {
 679          $user = defined('YOURLS_USER') ? YOURLS_USER : '-1';
 680      }
 681  
 682      // Get nonce value from $_REQUEST if not specified
 683      if( false === $nonce && isset( $_REQUEST['nonce'] ) ) {
 684          $nonce = $_REQUEST['nonce'];
 685      }
 686  
 687      // Allow plugins to short-circuit the rest of the function
 688      if (yourls_apply_filter( 'verify_nonce', false, $action, $nonce, $user, $return ) === true) {
 689          return true;
 690      }
 691  
 692      // What nonce should be
 693      $valid = yourls_create_nonce( $action, $user );
 694  
 695      if( $nonce === $valid ) {
 696          return true;
 697      } else {
 698          if( $return )
 699              die( $return );
 700          yourls_die( yourls__( 'Unauthorized action or expired link' ), yourls__( 'Error' ), 403 );
 701      }
 702  }
 703  
 704  /**
 705   * Check if YOURLS_USER comes from environment variables
 706   *
 707   * @since 1.8.2
 708   * @return bool  true if YOURLS_USER and YOURLS_PASSWORD are defined as environment variables
 709   */
 710  function yourls_is_user_from_env() {
 711      return yourls_apply_filter('is_user_from_env', getenv('YOURLS_USER') && getenv('YOURLS_PASSWORD'));
 712  
 713  }
 714  
 715  /**
 716   * Check if we should hash passwords in the config file
 717   *
 718   * By default, passwords are hashed. They are not if
 719   *    - there is no password in clear text in the config file (ie everything is already hashed)
 720   *    - the user defined constant YOURLS_NO_HASH_PASSWORD is true, see https://docs.yourls.org/guide/essentials/credentials.html#i-don-t-want-to-encrypt-my-password
 721   *    - YOURLS_USER and YOURLS_PASSWORD are provided by the environment, not the config file
 722   *
 723   * @since 1.8.2
 724   * @return bool
 725   */
 726  function yourls_maybe_hash_passwords() {
 727      $hash = true;
 728  
 729      if ( !yourls_has_cleartext_passwords()
 730           OR (yourls_skip_password_hashing())
 731           OR (yourls_is_user_from_env())
 732      ) {
 733          $hash = false;
 734      }
 735  
 736      return yourls_apply_filter('maybe_hash_password', $hash );
 737  }
 738  
 739  /**
 740   * Check if user setting for skipping password hashing is set
 741   *
 742   * @since 1.8.2
 743   * @return bool
 744   */
 745  function yourls_skip_password_hashing() {
 746      return yourls_apply_filter('skip_password_hashing', defined('YOURLS_NO_HASH_PASSWORD') && YOURLS_NO_HASH_PASSWORD);
 747  }


Generated: Wed Sep 28 05:10:02 2022 Cross-referenced by PHPXref 0.7.1