[ Index ]

PHP Cross Reference of WordPress Trunk (Updated Daily)

Search

title

Body

[close]

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

   1  <?php
   2  /**
   3   * Secrets API: WP_Secrets_Cipher class
   4   *
   5   * @package WordPress
   6   * @subpackage Secrets
   7   * @since 7.2.0
   8   */
   9  
  10  /**
  11   * Encrypts and decrypts a single record slot.
  12   *
  13   * A slot holds a per-secret data key wrapped by a master key, plus a value encrypted
  14   * under that data key.
  15   *
  16   * This class does not know where a master key comes from (that is
  17   * WP_Secrets_Key_Manager's job), does not know about the 'v'/current/previous record
  18   * envelope (that is assembled by the functions in secrets.php), and does not set
  19   * 'created' or 'needs_rotation' (those are facts about a write, not about the
  20   * cryptography). It knows exactly one thing: given a 32-byte master key and a single
  21   * slot's worth of material, encrypt or decrypt it correctly.
  22   *
  23   * @since 7.2.0
  24   */
  25  final class WP_Secrets_Cipher {
  26  
  27      /**
  28       * AAD purpose tag for a wrapped data key.
  29       *
  30       * @since 7.2.0
  31       * @var string
  32       */
  33      const AAD_DATA_KEY = 'wp-secrets-data-key-v1';
  34  
  35      /**
  36       * AAD purpose tag for an encrypted value.
  37       *
  38       * @since 7.2.0
  39       * @var string
  40       */
  41      const AAD_VALUE = 'wp-secrets-value-v1';
  42  
  43      /**
  44       * KDF context used to derive the fingerprint key from a master key.
  45       *
  46       * Exactly 8 bytes, as sodium_crypto_kdf_derive_from_key() requires.
  47       *
  48       * @since 7.2.0
  49       * @var string
  50       */
  51      const FINGERPRINT_KDF_CONTEXT = 'wpsecfpr';
  52  
  53      /**
  54       * Encrypts a plaintext into a single record slot.
  55       *
  56       * @since 7.2.0
  57       *
  58       * @param string $master_key 32-byte master key for this scope.
  59       * @param string $scope      'site' or 'network'.
  60       * @param int    $site_id    Binds the AAD to a specific blog for site scope; use
  61       *                           0 for network scope, which is not bound to any one blog.
  62       * @param string $name       The secret's namespaced name.
  63       * @param string $slot       A WP_Secret_Version constant.
  64       * @param string $plaintext  The value to encrypt.
  65       * @return array|WP_Error Slot array with keys 'dk', 'dk_nonce', 'ct', 'nonce',
  66       *                        'fingerprint' on success. WP_Error on failure.
  67       *
  68       * @phpstan-return array{dk: string, dk_nonce: string, ct: string, nonce: string, fingerprint: string}|WP_Error
  69       * @phpstan-param 'site'|'network' $scope
  70       * @phpstan-param WP_Secret_Version::CURRENT|WP_Secret_Version::PREVIOUS $slot
  71       */
  72  	public function encrypt_value(
  73          #[\SensitiveParameter]
  74          string $master_key,
  75          string $scope,
  76          int $site_id,
  77          string $name,
  78          string $slot,
  79          #[\SensitiveParameter]
  80          $plaintext
  81      ) {
  82          $check = $this->validate_common( $master_key, $scope, $site_id, $name, $slot );
  83  
  84          if ( is_wp_error( $check ) ) {
  85              return $check;
  86          }
  87  
  88          if ( ! is_string( $plaintext ) ) {
  89              return new WP_Error(
  90                  WP_SECRETS_ERROR_INVALID_VALUE,
  91                  __( 'Secret values must be strings.' )
  92              );
  93          }
  94  
  95          if ( ! function_exists( 'sodium_crypto_aead_xchacha20poly1305_ietf_encrypt' ) ) {
  96              return new WP_Error(
  97                  WP_SECRETS_ERROR_CRYPTO_UNAVAILABLE,
  98                  __( 'No libsodium implementation is available.' )
  99              );
 100          }
 101  
 102          $fingerprint = $this->fingerprint( $master_key, $plaintext );
 103  
 104          if ( is_wp_error( $fingerprint ) ) {
 105              return $fingerprint;
 106          }
 107  
 108          $data_key = random_bytes( SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES );
 109  
 110          $dk_nonce   = random_bytes( SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES );
 111          $wrapped_dk = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
 112              $data_key,
 113              $this->build_aad( self::AAD_DATA_KEY, $scope, $site_id, $name, $slot ),
 114              $dk_nonce,
 115              $master_key
 116          );
 117  
 118          $value_nonce = random_bytes( SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES );
 119          $ciphertext  = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
 120              $plaintext,
 121              $this->build_aad( self::AAD_VALUE, $scope, $site_id, $name, $slot ),
 122              $value_nonce,
 123              $data_key
 124          );
 125  
 126          wp_secrets_memzero( $data_key );
 127  
 128          return array(
 129              'dk'          => base64_encode( $wrapped_dk ),
 130              'dk_nonce'    => base64_encode( $dk_nonce ),
 131              'ct'          => base64_encode( $ciphertext ),
 132              'nonce'       => base64_encode( $value_nonce ),
 133              'fingerprint' => $fingerprint,
 134          );
 135      }
 136  
 137      /**
 138       * Decrypts a single record slot back to its plaintext.
 139       *
 140       * @since 7.2.0
 141       *
 142       * @param string $master_key 32-byte master key for this scope.
 143       * @param string $scope      'site' or 'network'. Must match what encrypt_value()
 144       *                           was called with, or decryption fails.
 145       * @param int    $site_id    Must match what encrypt_value() was called with.
 146       * @param string $name       Must match what encrypt_value() was called with.
 147       * @param string $slot       Must match what encrypt_value() was called with.
 148       * @param mixed  $record     The slot array previously returned by encrypt_value().
 149       * @return string|WP_Error Plaintext on success. WP_Error on failure.
 150       *
 151       * @phpstan-param 'site'|'network' $scope
 152       * @phpstan-param WP_Secret_Version::CURRENT|WP_Secret_Version::PREVIOUS $slot
 153       */
 154  	public function decrypt_value(
 155          #[\SensitiveParameter]
 156          string $master_key,
 157          string $scope,
 158          int $site_id,
 159          string $name,
 160          string $slot,
 161          $record
 162      ) {
 163          $check = $this->validate_common( $master_key, $scope, $site_id, $name, $slot );
 164  
 165          if ( is_wp_error( $check ) ) {
 166              return $check;
 167          }
 168  
 169          $decoded = $this->decode_record_fields( $record );
 170  
 171          if ( is_wp_error( $decoded ) ) {
 172              return $decoded;
 173          }
 174  
 175          if ( ! function_exists( 'sodium_crypto_aead_xchacha20poly1305_ietf_decrypt' ) ) {
 176              return new WP_Error(
 177                  WP_SECRETS_ERROR_CRYPTO_UNAVAILABLE,
 178                  __( 'No libsodium implementation is available.' )
 179              );
 180          }
 181  
 182          $data_key = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
 183              $decoded['dk'],
 184              $this->build_aad( self::AAD_DATA_KEY, $scope, $site_id, $name, $slot ),
 185              $decoded['dk_nonce'],
 186              $master_key
 187          );
 188  
 189          if ( ! is_string( $data_key ) ) {
 190              return new WP_Error(
 191                  WP_SECRETS_ERROR_DECRYPTION_FAILED,
 192                  __( "The secret's data key could not be decrypted." )
 193              );
 194          }
 195  
 196          $plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
 197              $decoded['ct'],
 198              $this->build_aad( self::AAD_VALUE, $scope, $site_id, $name, $slot ),
 199              $decoded['nonce'],
 200              $data_key
 201          );
 202  
 203          wp_secrets_memzero( $data_key );
 204  
 205          if ( ! is_string( $plaintext ) ) {
 206              return new WP_Error(
 207                  WP_SECRETS_ERROR_DECRYPTION_FAILED,
 208                  __( 'The secret value could not be decrypted.' )
 209              );
 210          }
 211  
 212          return $plaintext;
 213      }
 214  
 215      /**
 216       * Computes the keyed fingerprint of a plaintext under a master key.
 217       *
 218       * Keyed so a fingerprint is not a cross-site rainbow-table oracle: the same
 219       * plaintext fingerprints differently under a different master key. Callers
 220       * verifying a value against a previously stored fingerprint (for example, a
 221       * migration's verify-before-delete step) must recompute this from freshly
 222       * decrypted plaintext and compare – never trust a fingerprint read back from a
 223       * record, which sits outside the AAD and is not authenticated.
 224       *
 225       * @since 7.2.0
 226       *
 227       * @param string $master_key 32-byte master key.
 228       * @param string $plaintext  Value to fingerprint.
 229       * @return string|WP_Error 32-character hex string on success. WP_Error on failure.
 230       */
 231  	public function fingerprint(
 232          #[\SensitiveParameter]
 233          string $master_key,
 234          #[\SensitiveParameter]
 235          $plaintext
 236      ) {
 237          if ( ! $this->is_valid_master_key( $master_key ) ) {
 238              return new WP_Error(
 239                  WP_SECRETS_ERROR_KEY_UNAVAILABLE,
 240                  __( 'A 32-byte master key is required.' )
 241              );
 242          }
 243  
 244          if ( ! is_string( $plaintext ) ) {
 245              return new WP_Error(
 246                  WP_SECRETS_ERROR_INVALID_VALUE,
 247                  __( 'Secret values must be strings.' )
 248              );
 249          }
 250  
 251          if ( ! function_exists( 'sodium_crypto_kdf_derive_from_key' ) || ! function_exists( 'sodium_crypto_generichash' ) ) {
 252              return new WP_Error(
 253                  WP_SECRETS_ERROR_CRYPTO_UNAVAILABLE,
 254                  __( 'No libsodium implementation is available.' )
 255              );
 256          }
 257  
 258          $fingerprint_key = sodium_crypto_kdf_derive_from_key( 32, 1, self::FINGERPRINT_KDF_CONTEXT, $master_key );
 259          $fingerprint     = sodium_crypto_generichash( $plaintext, $fingerprint_key, 16 );
 260  
 261          wp_secrets_memzero( $fingerprint_key );
 262  
 263          return bin2hex( $fingerprint );
 264      }
 265  
 266      /**
 267       * Builds the AAD that binds a ciphertext to its full context.
 268       *
 269       * Binding covers purpose, scope, site, name, and slot, so that a record can never
 270       * be replayed under any of them.
 271       *
 272       * Centralized in one place rather than inlined at each call site, and only ever
 273       * called after validate_common() has confirmed $name passes
 274       * wp_secrets_validate_name() – the validated character set contains no '|', which
 275       * is what makes this delimiter safe to join on.
 276       *
 277       * @since 7.2.0
 278       *
 279       * @param string $purpose One of the AAD_* class constants.
 280       * @param string $scope   'site' or 'network'.
 281       * @param int    $site_id Blog ID for site scope, 0 for network scope.
 282       * @param string $name    Validated secret name.
 283       * @param string $slot    A WP_Secret_Version constant.
 284       * @return string
 285       *
 286       * @phpstan-param 'site'|'network' $scope
 287       * @phpstan-param WP_Secret_Version::CURRENT|WP_Secret_Version::PREVIOUS $slot
 288       */
 289  	private function build_aad( string $purpose, string $scope, int $site_id, string $name, string $slot ): string {
 290          return sprintf( '%s|%s|%d|%s|%s', $purpose, $scope, $site_id, $name, $slot );
 291      }
 292  
 293      /**
 294       * Validates the parameters shared by encrypt_value() and decrypt_value().
 295       *
 296       * $scope, $site_id, and $slot are never influenced by external input – every
 297       * call site in this API supplies them internally – so a bad value here means
 298       * the calling code is wrong, not that a runtime condition failed. That still
 299       * reports as a WP_Error rather than an exception: WordPress functions return
 300       * WP_Error or false, they do not throw. The _doing_it_wrong() notice is what
 301       * makes the distinction visible during development. $name and $master_key
 302       * legitimately vary at runtime (a plugin author's typo, an unavailable key
 303       * backend) and have always reported the same way.
 304       *
 305       * @since 7.2.0
 306       *
 307       * @param string $master_key Candidate master key.
 308       * @param string $scope      Candidate scope.
 309       * @param int    $site_id    Candidate site ID.
 310       * @param string $name       Candidate secret name.
 311       * @param string $slot       Candidate slot.
 312       * @return true|WP_Error
 313       *
 314       * @phpstan-param 'site'|'network' $scope
 315       * @phpstan-param WP_Secret_Version::CURRENT|WP_Secret_Version::PREVIOUS $slot
 316       */
 317  	private function validate_common(
 318          #[\SensitiveParameter]
 319          string $master_key,
 320          string $scope,
 321          int $site_id,
 322          string $name,
 323          string $slot
 324      ) {
 325          if ( ! in_array( $scope, array( 'site', 'network' ), true ) ) {
 326              return $this->invalid_argument( __( 'The scope must be "site" or "network".' ) );
 327          }
 328  
 329          if ( $site_id < 0 ) {
 330              return $this->invalid_argument( __( 'The site id must be a non-negative integer.' ) );
 331          }
 332  
 333          if ( ! in_array( $slot, array( WP_Secret_Version::CURRENT, WP_Secret_Version::PREVIOUS ), true ) ) {
 334              return $this->invalid_argument( __( 'The slot must be a WP_Secret_Version constant.' ) );
 335          }
 336  
 337          if ( ! $this->is_valid_master_key( $master_key ) ) {
 338              return new WP_Error(
 339                  WP_SECRETS_ERROR_KEY_UNAVAILABLE,
 340                  __( 'A 32-byte master key is required.' )
 341              );
 342          }
 343  
 344          $name_check = wp_secrets_validate_name( $name );
 345  
 346          if ( is_wp_error( $name_check ) ) {
 347              return $name_check;
 348          }
 349  
 350          return true;
 351      }
 352  
 353      /**
 354       * Reports a caller error the way WordPress does.
 355       *
 356       * Emits a _doing_it_wrong() notice for the developer, and returns a WP_Error the
 357       * caller can act on.
 358       *
 359       * @since 7.2.0
 360       *
 361       * @param string $message What the caller got wrong.
 362       * @return WP_Error
 363       */
 364  	private function invalid_argument( string $message ): WP_Error {
 365          _doing_it_wrong( __CLASS__ . '::encrypt_value()/decrypt_value()', $message, '7.2.0' );
 366  
 367          return new WP_Error( WP_SECRETS_ERROR_INVALID_ARGUMENT, $message );
 368      }
 369  
 370      /**
 371       * Whether a candidate value is usable as a 32-byte master key.
 372       *
 373       * @since 7.2.0
 374       *
 375       * @param string $master_key Candidate master key.
 376       * @return bool
 377       */
 378  	private function is_valid_master_key( string $master_key ): bool {
 379          return SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_KEYBYTES === strlen( $master_key );
 380      }
 381  
 382      /**
 383       * Validates and base64-decodes the four crypto fields of a record slot.
 384       *
 385       * @since 7.2.0
 386       *
 387       * @param mixed $record Candidate slot array.
 388       * @return array<string, string>|WP_Error Decoded ('dk', 'dk_nonce', 'ct', 'nonce') on success.
 389       */
 390  	private function decode_record_fields( $record ) {
 391          if ( ! is_array( $record ) ) {
 392              return new WP_Error(
 393                  WP_SECRETS_ERROR_RECORD_MALFORMED,
 394                  __( 'Secret record slot must be an array.' )
 395              );
 396          }
 397  
 398          $decoded = array();
 399  
 400          foreach ( array( 'dk', 'dk_nonce', 'ct', 'nonce' ) as $field ) {
 401              if ( ! isset( $record[ $field ] ) || ! is_string( $record[ $field ] ) ) {
 402                  return new WP_Error(
 403                      WP_SECRETS_ERROR_RECORD_MALFORMED,
 404                      sprintf(
 405                          /* translators: %s: Record field name. */
 406                          __( 'Secret record slot is missing the "%s" field.' ),
 407                          $field
 408                      )
 409                  );
 410              }
 411  
 412              $value = base64_decode( $record[ $field ], true );
 413  
 414              if ( false === $value ) {
 415                  return new WP_Error(
 416                      WP_SECRETS_ERROR_RECORD_MALFORMED,
 417                      sprintf(
 418                          /* translators: %s: Record field name. */
 419                          __( 'Secret record slot field "%s" is not valid base64.' ),
 420                          $field
 421                      )
 422                  );
 423              }
 424  
 425              $decoded[ $field ] = $value;
 426          }
 427  
 428          if ( SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES !== strlen( $decoded['dk_nonce'] )
 429              || SODIUM_CRYPTO_AEAD_XCHACHA20POLY1305_IETF_NPUBBYTES !== strlen( $decoded['nonce'] ) ) {
 430              return new WP_Error(
 431                  WP_SECRETS_ERROR_RECORD_MALFORMED,
 432                  __( 'Secret record slot has a malformed nonce.' )
 433              );
 434          }
 435  
 436          return $decoded;
 437      }
 438  }


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