[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

/wp-includes/secrets/ -> class-wp-secrets-key-manager.php (source)

   1  <?php
   2  /**
   3   * Secrets API: WP_Secrets_Key_Manager class
   4   *
   5   * @package WordPress
   6   * @subpackage Secrets
   7   * @since 7.2.0
   8   */
   9  
  10  /**
  11   * Manages the root key and derives per-scope master keys from it.
  12   *
  13   * Owns the root key's generation, storage, and rotation.
  14   *
  15   * There is exactly one root key per install: 32 random bytes, generated once, wrapped
  16   * by the active WP_Secrets_Keyring, and stored via update_site_option() (which is a
  17   * plain option on single-site, and network-wide on multisite). It is the only value a
  18   * site-key rotation ever re-wraps, on a single site or on a 500-site network.
  19   *
  20   * Master keys are derived from the root key on demand and never stored:
  21   *
  22   * - Site scope, blog N: sodium_crypto_kdf_derive_from_key( 32, N, 'wpsecsit', $root ).
  23   *   Distinct per blog, which shared network-wide salts otherwise cannot provide.
  24   * - Network scope: sodium_crypto_kdf_derive_from_key( 32, 0, 'wpsecnet', $root ).
  25   *   Subkey ID 0 is reserved for this (blog IDs start at 1) and the context string
  26   *   differs from the site path, so there is no collision between the two. Identical
  27   *   on every blog, so a network secret written on one blog reads on every other.
  28   *
  29   * One unwrapped copy of the root key lives in this object for the rest of the
  30   * request, in memory only, never in the object cache. It is replaced whenever the
  31   * stored wrapped value changes – a rotation, a re-wrap, a restore – so it is never
  32   * stale. Callers of get_root_key() still receive a copy and must zero it themselves;
  33   * this object's own copy is not theirs to zero. The practical effect: a remote
  34   * keyring (a KMS or HSM call) is invoked once per request, not once per secret.
  35   *
  36   * @since 7.2.0
  37   */
  38  final class WP_Secrets_Key_Manager {
  39  
  40      /**
  41       * Option name the wrapped root key is stored under.
  42       *
  43       * Always accessed through the *_site_option() functions directly, never through a
  44       * WP_Secrets_Store. Swapping the pluggable secret store therefore never relocates
  45       * the root key, and swapping the keyring never affects where ciphertext lives.
  46       *
  47       * @since 7.2.0
  48       * @var string
  49       */
  50      const ROOT_KEY_OPTION = '_wp_secrets_root_key';
  51  
  52      /**
  53       * KDF context for deriving a site-scope master key. Exactly 8 bytes.
  54       *
  55       * @since 7.2.0
  56       * @var string
  57       */
  58      const SITE_KDF_CONTEXT = 'wpsecsit';
  59  
  60      /**
  61       * KDF context for deriving the network-scope master key. Exactly 8 bytes.
  62       *
  63       * @since 7.2.0
  64       * @var string
  65       */
  66      const NETWORK_KDF_CONTEXT = 'wpsecnet';
  67  
  68      /**
  69       * Reserved KDF subkey ID for network scope.
  70       *
  71       * Blog IDs start at 1, so this can never collide with a site-scope subkey ID.
  72       *
  73       * @since 7.2.0
  74       * @var int
  75       */
  76      const NETWORK_SUBKEY_ID = 0;
  77  
  78      /**
  79       * The keyring used to wrap and unwrap the root key.
  80       *
  81       * @since 7.2.0
  82       * @var WP_Secrets_Keyring
  83       */
  84      private $keyring;
  85  
  86      /**
  87       * The unwrapped root key currently cached for this request, or null if nothing
  88       * has been unwrapped yet.
  89       *
  90       * @since 7.2.0
  91       * @var string|null
  92       */
  93      private $cached_root_key = null;
  94  
  95      /**
  96       * The wrapped value $cached_root_key was unwrapped from, or null if nothing has
  97       * been unwrapped yet. Used to detect that the stored wrapped value changed
  98       * underneath this object (a rotation, a re-wrap, a restore) so the cache is not
  99       * served stale.
 100       *
 101       * @since 7.2.0
 102       * @var string|null
 103       */
 104      private $cached_wrapped = null;
 105  
 106      /**
 107       * Constructor.
 108       *
 109       * @since 7.2.0
 110       *
 111       * @param WP_Secrets_Keyring|null $keyring Keyring to use. Defaults to the
 112       *                                         built-in config-based provider.
 113       */
 114  	public function __construct( ?WP_Secrets_Keyring $keyring = null ) {
 115          $this->keyring = $keyring ? $keyring : new WP_Secrets_Config_Key_Provider();
 116      }
 117  
 118      /**
 119       * Returns the keyring in use.
 120       *
 121       * Used by Site Health and by `wp secret dropin` and `wp secret health`, which all
 122       * need to describe the active keyring without duplicating the logic that resolves
 123       * it.
 124       *
 125       * @since 7.2.0
 126       *
 127       * @return WP_Secrets_Keyring
 128       */
 129  	public function get_keyring(): WP_Secrets_Keyring {
 130          return $this->keyring;
 131      }
 132  
 133      /**
 134       * Derives a scope's master key from the root key.
 135       *
 136       * @since 7.2.0
 137       *
 138       * @param string   $scope           'site' or 'network'.
 139       * @param int|null $site_id         Blog ID for site scope. Defaults to the current blog.
 140       *                                  Ignored for network scope.
 141       * @param bool     $create_root_key Optional. Whether to generate and store a root key
 142       *                                  if none exists. Pass false when only reading
 143       *                                  secrets. Default true.
 144       * @return string|WP_Error 32-byte master key on success. WP_Error on failure,
 145       *                         including when a caller passes an invalid scope or
 146       *                         site ID – see WP_Secrets_Cipher::validate_common()
 147       *                         for why that is a WP_Error and not an exception.
 148       *
 149       * @phpstan-param 'site'|'network' $scope
 150       */
 151  	public function get_master_key( string $scope, ?int $site_id = null, bool $create_root_key = true ) {
 152          if ( ! in_array( $scope, array( 'site', 'network' ), true ) ) {
 153              $message = __( 'The scope must be "site" or "network".' );
 154  
 155              _doing_it_wrong( __METHOD__, $message, '7.2.0' );
 156  
 157              return new WP_Error( WP_SECRETS_ERROR_INVALID_ARGUMENT, $message );
 158          }
 159  
 160          if ( 'network' === $scope ) {
 161              $subkey_id = self::NETWORK_SUBKEY_ID;
 162              $context   = self::NETWORK_KDF_CONTEXT;
 163          } else {
 164              $subkey_id = $site_id ?? get_current_blog_id();
 165  
 166              if ( $subkey_id < 1 ) {
 167                  $message = __( 'The site id must be a positive integer.' );
 168  
 169                  _doing_it_wrong( __METHOD__, $message, '7.2.0' );
 170  
 171                  return new WP_Error( WP_SECRETS_ERROR_INVALID_ARGUMENT, $message );
 172              }
 173  
 174              $context = self::SITE_KDF_CONTEXT;
 175          }
 176  
 177          $root_key = $this->get_root_key( $create_root_key );
 178  
 179          if ( is_wp_error( $root_key ) ) {
 180              return $root_key;
 181          }
 182  
 183          if ( ! function_exists( 'sodium_crypto_kdf_derive_from_key' ) ) {
 184              wp_secrets_memzero( $root_key );
 185  
 186              return new WP_Error(
 187                  WP_SECRETS_ERROR_CRYPTO_UNAVAILABLE,
 188                  __( 'No libsodium implementation is available.' )
 189              );
 190          }
 191  
 192          $master_key = sodium_crypto_kdf_derive_from_key( 32, $subkey_id, $context, $root_key );
 193  
 194          wp_secrets_memzero( $root_key );
 195  
 196          return $master_key;
 197      }
 198  
 199      /**
 200       * Returns the root key, generating and persisting one on first use.
 201       *
 202       * get_site_option() also returns false when its query fails, so a false result is
 203       * checked against the database before a new root key is generated. Generating one
 204       * while another is stored would make every existing secret undecryptable.
 205       *
 206       * @since 7.2.0
 207       *
 208       * @param bool $create Optional. Whether to generate and store a root key if none
 209       *                     exists. Default true.
 210       * @return string|WP_Error 32 raw bytes on success. WP_Error on failure.
 211       */
 212  	public function get_root_key( bool $create = true ) {
 213          $wrapped = $this->get_wrapped_root_key();
 214  
 215          if ( false === $wrapped ) {
 216              $wrapped = $this->read_stored_root_key();
 217  
 218              if ( is_wp_error( $wrapped ) ) {
 219                  return $wrapped;
 220              }
 221  
 222              if ( false === $wrapped ) {
 223                  if ( ! $create ) {
 224                      return new WP_Error(
 225                          WP_SECRETS_ERROR_KEY_UNAVAILABLE,
 226                          __( 'No root key is stored.' )
 227                      );
 228                  }
 229  
 230                  return $this->generate_root_key();
 231              }
 232          }
 233  
 234          if ( ! is_string( $wrapped ) ) {
 235              return new WP_Error(
 236                  WP_SECRETS_ERROR_RECORD_MALFORMED,
 237                  __( 'The stored root key is not a string.' )
 238              );
 239          }
 240  
 241          if ( null !== $this->cached_root_key && $wrapped === $this->cached_wrapped ) {
 242              return $this->cached_root_key;
 243          }
 244  
 245          $root_key = $this->keyring->unwrap( $wrapped );
 246  
 247          if ( is_string( $root_key ) ) {
 248              $this->cached_wrapped  = $wrapped;
 249              $this->cached_root_key = $root_key;
 250          }
 251  
 252          return $root_key;
 253      }
 254  
 255      /**
 256       * Re-wraps the root key under a new keyring, without touching any stored secret.
 257       *
 258       * Every derived master key is unchanged by this: they come from the root key's
 259       * raw bytes, which rotation never alters, only its wrapping. No secret value is
 260       * ever re-encrypted as a result of a site-key rotation.
 261       *
 262       * @since 7.2.0
 263       *
 264       * @param WP_Secrets_Keyring $old_keyring Unwraps the current wrapped root key.
 265       * @param WP_Secrets_Keyring $new_keyring Wraps it again for storage.
 266       * @return true|WP_Error
 267       */
 268  	public function rotate_site_key( WP_Secrets_Keyring $old_keyring, WP_Secrets_Keyring $new_keyring ) {
 269          $wrapped = $this->get_wrapped_root_key();
 270  
 271          if ( ! is_string( $wrapped ) ) {
 272              return new WP_Error(
 273                  WP_SECRETS_ERROR_STORE_UNAVAILABLE,
 274                  __( 'No root key exists to rotate.' )
 275              );
 276          }
 277  
 278          if ( $old_keyring === $this->keyring && null !== $this->cached_root_key && $wrapped === $this->cached_wrapped ) {
 279              $root_key = $this->cached_root_key;
 280          } else {
 281              $root_key = $old_keyring->unwrap( $wrapped );
 282          }
 283  
 284          if ( is_wp_error( $root_key ) ) {
 285              return $root_key;
 286          }
 287  
 288          $rewrapped = $new_keyring->wrap( $root_key );
 289  
 290          if ( is_wp_error( $rewrapped ) ) {
 291              wp_secrets_memzero( $root_key );
 292  
 293              return $rewrapped;
 294          }
 295  
 296          /*
 297           * update_site_option() returns false both on genuine failure and when the
 298           * new value equals the old one – a documented ambiguity shared with
 299           * update_option(). In practice this never collides here: wrap() draws a
 300           * fresh random nonce every call, so the re-wrapped value is only equal to
 301           * the old one if this call somehow re-wrapped under the exact same nonce,
 302           * astronomically unlikely.
 303           */
 304          if ( ! update_site_option( self::ROOT_KEY_OPTION, $rewrapped ) ) {
 305              wp_secrets_memzero( $root_key );
 306  
 307              return new WP_Error(
 308                  WP_SECRETS_ERROR_STORE_UNAVAILABLE,
 309                  __( 'Could not store the re-wrapped root key.' )
 310              );
 311          }
 312  
 313          $this->cached_wrapped  = $rewrapped;
 314          $this->cached_root_key = $root_key;
 315  
 316          wp_secrets_memzero( $root_key );
 317  
 318          return true;
 319      }
 320  
 321      /**
 322       * Returns the wrapped root key, adopting a pre-conversion copy if needed.
 323       *
 324       * A single site converted to multisite keeps its wrapped root key in its own
 325       * (now main site's) options row: `update_site_option()` only starts writing to
 326       * sitemeta once `is_multisite()` is true, and the conversion process does not
 327       * move existing option rows. Without this, a network's first read would find no
 328       * sitemeta row and mint a brand new root key, stranding every secret written
 329       * before conversion.
 330       *
 331       * @since 7.2.0
 332       *
 333       * @return mixed The wrapped root key, or false if none exists anywhere. Anything
 334       *               but a string or false is a corrupt row, which the caller reports.
 335       */
 336  	private function get_wrapped_root_key() {
 337          $wrapped = get_site_option( self::ROOT_KEY_OPTION );
 338  
 339          if ( false !== $wrapped || ! is_multisite() ) {
 340              return $wrapped;
 341          }
 342  
 343          $main_site_id = get_main_site_id();
 344          $legacy       = get_blog_option( $main_site_id, self::ROOT_KEY_OPTION );
 345  
 346          if ( ! is_string( $legacy ) ) {
 347              return false;
 348          }
 349  
 350          if ( add_site_option( self::ROOT_KEY_OPTION, $legacy ) ) {
 351              delete_blog_option( $main_site_id, self::ROOT_KEY_OPTION );
 352          }
 353  
 354          // Re-read: handles a concurrent request that already adopted it.
 355          return get_site_option( self::ROOT_KEY_OPTION );
 356      }
 357  
 358      /**
 359       * Generates a new root key and persists it.
 360       *
 361       * Handles the race where two requests both find no root key at the same time.
 362       *
 363       * @since 7.2.0
 364       *
 365       * @global wpdb $wpdb WordPress database abstraction object.
 366       *
 367       * @return string|WP_Error
 368       */
 369  	private function generate_root_key() {
 370          global $wpdb;
 371  
 372          $candidate = random_bytes( 32 );
 373  
 374          $wrapped = $this->keyring->wrap( $candidate );
 375  
 376          if ( is_wp_error( $wrapped ) ) {
 377              wp_secrets_memzero( $candidate );
 378  
 379              return $wrapped;
 380          }
 381  
 382          $inserted_row_id = $this->insert_root_key( $wrapped );
 383  
 384          // Use whichever root key is stored now: this one, or one another request stored first.
 385          $existing = $this->read_stored_root_key();
 386  
 387          if ( is_string( $existing ) && hash_equals( $existing, $wrapped ) ) {
 388              $this->cached_wrapped  = $wrapped;
 389              $this->cached_root_key = $candidate;
 390  
 391              return $candidate;
 392          }
 393  
 394          // Lost the race: another request created one first. Use theirs, not ours.
 395          wp_secrets_memzero( $candidate );
 396  
 397          if ( $inserted_row_id ) {
 398              $wpdb->delete( $wpdb->sitemeta, array( 'meta_id' => $inserted_row_id ) );
 399          }
 400  
 401          if ( is_wp_error( $existing ) ) {
 402              return $existing;
 403          }
 404  
 405          if ( false === $existing ) {
 406              return new WP_Error(
 407                  WP_SECRETS_ERROR_STORE_UNAVAILABLE,
 408                  __( 'Could not store the root key.' )
 409              );
 410          }
 411  
 412          $root_key = $this->keyring->unwrap( $existing );
 413  
 414          if ( is_string( $root_key ) ) {
 415              $this->cached_wrapped  = $existing;
 416              $this->cached_root_key = $root_key;
 417          }
 418  
 419          return $root_key;
 420      }
 421  
 422      /**
 423       * Stores a new wrapped root key unless one is already stored.
 424       *
 425       * This does not use add_site_option(). On a single site that is add_option(), which
 426       * skips its existence check for an option cached as missing and then overwrites the
 427       * stored row, so a failed read followed by add_option() would replace the root key.
 428       *
 429       * @since 7.2.0
 430       *
 431       * @global wpdb $wpdb WordPress database abstraction object.
 432       *
 433       * @param string $wrapped The wrapped root key.
 434       * @return int ID of the inserted wp_sitemeta row on multisite, 0 otherwise.
 435       */
 436  	private function insert_root_key( string $wrapped ): int {
 437          global $wpdb;
 438  
 439          $value = maybe_serialize( $wrapped );
 440  
 441          if ( ! is_multisite() ) {
 442              // The unique key on option_name makes this a no-op when a root key exists.
 443              $wpdb->query(
 444                  $wpdb->prepare(
 445                      "INSERT IGNORE INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, 'off')",
 446                      self::ROOT_KEY_OPTION,
 447                      $value
 448                  )
 449              );
 450  
 451              return 0;
 452          }
 453  
 454          /*
 455           * wp_sitemeta has no unique key on meta_key, so two requests can both insert a
 456           * row. read_stored_root_key() returns the oldest row, so both end up with the
 457           * same root key, and the request that lost deletes its own row.
 458           */
 459          $inserted = $wpdb->insert(
 460              $wpdb->sitemeta,
 461              array(
 462                  'site_id'    => get_current_network_id(),
 463                  'meta_key'   => self::ROOT_KEY_OPTION,
 464                  'meta_value' => $value,
 465              )
 466          );
 467  
 468          return $inserted ? (int) $wpdb->insert_id : 0;
 469      }
 470  
 471      /**
 472       * Reads the wrapped root key from the database, bypassing the options cache.
 473       *
 474       * get_site_option() returns false both when the root key does not exist and when
 475       * its query failed, and caches the option as missing either way. This read tells
 476       * the two apart. When the row exists, it also clears that cache entry.
 477       *
 478       * @since 7.2.0
 479       *
 480       * @global wpdb $wpdb WordPress database abstraction object.
 481       *
 482       * @return string|false|WP_Error The wrapped root key, false if none is stored, or
 483       *                               WP_Error if the read failed or the row is malformed.
 484       */
 485  	private function read_stored_root_key() {
 486          global $wpdb;
 487  
 488          if ( is_multisite() ) {
 489              $value = $wpdb->get_var(
 490                  $wpdb->prepare(
 491                      "SELECT meta_value FROM $wpdb->sitemeta WHERE meta_key = %s AND site_id = %d ORDER BY meta_id ASC LIMIT 1",
 492                      self::ROOT_KEY_OPTION,
 493                      get_current_network_id()
 494                  )
 495              );
 496          } else {
 497              $value = $wpdb->get_var(
 498                  $wpdb->prepare(
 499                      "SELECT option_value FROM $wpdb->options WHERE option_name = %s LIMIT 1",
 500                      self::ROOT_KEY_OPTION
 501                  )
 502              );
 503          }
 504  
 505          if ( '' !== $wpdb->last_error ) {
 506              return new WP_Error(
 507                  WP_SECRETS_ERROR_STORE_UNAVAILABLE,
 508                  __( 'Could not read the root key.' )
 509              );
 510          }
 511  
 512          if ( null === $value ) {
 513              return false;
 514          }
 515  
 516          $this->forget_missing_root_key();
 517  
 518          $value = maybe_unserialize( $value );
 519  
 520          if ( ! is_string( $value ) ) {
 521              return new WP_Error(
 522                  WP_SECRETS_ERROR_RECORD_MALFORMED,
 523                  __( 'The stored root key is not a string.' )
 524              );
 525          }
 526  
 527          return $value;
 528      }
 529  
 530      /**
 531       * Removes the root key from the cache of options that do not exist.
 532       *
 533       * @since 7.2.0
 534       */
 535  	private function forget_missing_root_key(): void {
 536          if ( is_multisite() ) {
 537              $network_id     = get_current_network_id();
 538              $group          = 'site-options';
 539              $notoptions_key = "$network_id:notoptions";
 540  
 541              wp_cache_delete( "$network_id:" . self::ROOT_KEY_OPTION, $group );
 542          } else {
 543              $group          = 'options';
 544              $notoptions_key = 'notoptions';
 545  
 546              wp_cache_delete( self::ROOT_KEY_OPTION, $group );
 547          }
 548  
 549          $notoptions = wp_cache_get( $notoptions_key, $group );
 550  
 551          if ( is_array( $notoptions ) && isset( $notoptions[ self::ROOT_KEY_OPTION ] ) ) {
 552              unset( $notoptions[ self::ROOT_KEY_OPTION ] );
 553              wp_cache_set( $notoptions_key, $notoptions, $group );
 554          }
 555      }
 556  }


Generated : Mon Nov 16 08:20:01 2026 Cross-referenced by PHPXref