Skip to content

Security: Hash wp_signups.activation_key (Trac #38474, CVE-2017-14990)#12235

Open
bor0 wants to merge 8 commits into
WordPress:trunkfrom
bor0:fix/38474-hash-signup-activation-keys
Open

Security: Hash wp_signups.activation_key (Trac #38474, CVE-2017-14990)#12235
bor0 wants to merge 8 commits into
WordPress:trunkfrom
bor0:fix/38474-hash-signup-activation-keys

Conversation

@bor0

@bor0 bor0 commented Jun 19, 2026

Copy link
Copy Markdown
Member

Summary

  • wp_signups.activation_key stored activation keys as plain text. This patches it to use HMAC-SHA256, following a suggestion from @dmsnell in the ticket thread.
  • On signup: a triplet email:timestamp:random_key is built; base64(HMAC-SHA256(triplet, AUTH_KEY+AUTH_SALT)) (44 chars) is stored in the DB; base64url(triplet) is sent in the activation email.
  • On activation: the triplet is decoded from the URL, the HMAC is recomputed, and the row is fetched via WHERE user_email = %s AND activation_key = %s — a direct indexed lookup, no extra URL parameter needed.
  • Legacy plain-text keys (pre-upgrade pending activations) continue to work via a fallback path — detected by matching the original [0-9a-f]{16} format — so no pending activations are broken by the upgrade. Legacy keys are also now subject to the same expiration check (via registered column) as new keys.
  • A new activate_signup_expiration filter (default: DAY_IN_SECONDS) controls key expiry, checked from the timestamp embedded in the triplet for new keys, and from $signup->registered for legacy keys.
  • Key generation is extracted into a private _wp_generate_signup_key() helper used by both signup functions, with random_bytes() where available. A companion _wp_resolve_signup_key() helper handles parsing and DB-lookup-key resolution for both new and legacy formats.
  • Note: activation links are invalidated when the site's authentication keys or salts change, consistent with how WordPress already invalidates login sessions on salt rotation.
  • 10 new PHPUnit tests (including a legacy-schema column-length check and an expired legacy key test); one existing test fixed to work with the new format.

Fixes #38474. See also: https://core.trac.wordpress.org/ticket/38474

Props bor0, tomdxw, jeremyfelt, SergeyBiryukov, SirLouen, dmsnell, peterwilsoncc.

Test plan

Automated (PHPUnit)

npm install
# edit .env: set LOCAL_MULTISITE=true
npm run env:start
npm run env:install

# New tests:
npm run test:php -- -c tests/phpunit/multisite.xml --filter Tests_Multisite_wpmuActivateSignup

# Fixed regression test:
npm run test:php -- -c tests/phpunit/multisite.xml --filter test_should_not_fail_for_data_used_by_a_deleted_user

All 10 tests should pass.

Manual

  1. Hashed key in DB — Register at /wp-signup.php as a logged-out user. Check wp_signups.activation_key: should be a ~44-char base64 string (e.g. 5c4hlLJIcvtSnse3cuKo93pVWx2KBNOPan4HHpN7mfs=), not a plain hex string.

  2. Activation link works — The confirmation email link contains just key=<base64url_triplet> (no signup_id). Clicking it shows "Your account is now active!"

  3. Wrong key rejected — Visit /wp-activate.php?key=WRONGKEY. Activation must fail.

  4. Legacy key BC — Insert a row into wp_signups with a 16-char hex activation_key and a recent registered timestamp. Visiting /wp-activate.php?key=<hex_key> should still succeed — existing pending activations must not break after upgrade.

  5. Expired legacy key rejected — Insert a row into wp_signups with a 16-char hex activation_key and a registered timestamp older than DAY_IN_SECONDS. Activation must fail with an expired-key error.

  6. Expiry (new format) — Add add_filter('activate_signup_expiration', fn() => -1) to an mu-plugin, sign up, try to activate. Must fail with an expired-key error.

🤖 Generated with Claude Code

`wp_signups.activation_key` stored activation keys as plain text
(e.g. `7259c714857ef009`), unlike `wp_users.user_activation_key`
which already stores a `timestamp:hash` pair. This was assigned
CVE-2017-14990.

This patch brings `wp_signups` into line with `wp_users`:

- `wpmu_signup_blog()` and `wpmu_signup_user()` now hash the key
  with phpass before storing it (`timestamp:phpass_hash` format),
  mirroring the approach used for password-reset keys in [25696].
- `wpmu_activate_signup()` verifies the submitted key against the
  stored hash and enforces a 24-hour expiry via the new
  `activate_signup_expiration` filter.
- Legacy plain-text keys (rows created before the upgrade) continue
  to work for backwards compatibility so no pending activations are
  broken by the upgrade.
- Activation URLs now include `&signup_id=N` so the correct row can
  be fetched for hash verification without a full-table scan.
- `wp-activate.php` gains a Signup ID field on the manual
  activation form.
- Unit tests cover: hashed storage, successful activation, wrong
  key rejection, wrong signup_id rejection, legacy key BC, expiry,
  and the `activate_signup_expiration` filter.

Props bor0, tomdxw, jeremyfelt, SergeyBiryukov, SirLouen, dmsnell.
Fixes #38474.

== Testing Instructions ==

=== Automated (PHPUnit) ===

Requires the Docker-based local environment:

  npm install
  # edit .env: set LOCAL_MULTISITE=true
  npm run env:start
  npm run env:install

  # New tests for this ticket:
  npm run test:php -- -c tests/phpunit/multisite.xml \
    --filter Tests_Multisite_wpmuActivateSignup

  # Regression: existing test that was updated:
  npm run test:php -- -c tests/phpunit/multisite.xml \
    --filter test_should_not_fail_for_data_used_by_a_deleted_user

All 9 tests should pass.

=== Manual (browser) ===

1. HASHED KEY IN DB
   - Go to /wp-signup.php as a logged-out user and register.
   - Check wp_signups: activation_key should look like
     "1700000000:$P$Bxxx..." not a plain 16-char hex string.

2. ACTIVATION LINK WORKS
   - The confirmation email link includes both key= and signup_id=.
   - Clicking it shows "Your account is now active!"

3. SIGNUP ID FIELD ON FORM
   - Visit /wp-activate.php with no params.
   - The manual entry form should show both "Activation Key"
     and "Signup ID" fields.

4. WRONG KEY REJECTED
   - Visit /wp-activate.php?key=WRONGKEY&signup_id=<valid_id>
   - Activation must fail (no "now active" message).

5. LEGACY KEY BACKWARDS COMPAT
   - Insert a row with a plain-text activation_key directly into
     wp_signups (simulating a pre-upgrade pending activation).
   - Visit /wp-activate.php?key=<plain_key>&signup_id=<id>
   - Activation should succeed -- pre-upgrade pending activations
     must not be broken by the upgrade.

6. EXPIRY
   - Add add_filter('activate_signup_expiration', fn() => -1)
     to an mu-plugin, sign up, try to activate.
   - Activation should fail with an expired-key error.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Hi there! 👋

Thank you for your contribution to WordPress! 💖

It looks like this is your first pull request to wordpress-develop. Here are a few things to be aware of that may help you out!

No one monitors this repository for new pull requests. Pull requests must be attached to a Trac ticket to be considered for inclusion in WordPress Core. To attach a pull request to a Trac ticket, please include the ticket's full URL in your pull request description.

Pull requests are never merged on GitHub. The WordPress codebase continues to be managed through the SVN repository that this GitHub repository mirrors. Please feel free to open pull requests to work on any contribution you are making.

More information about how GitHub pull requests can be used to contribute to WordPress can be found in the Core Handbook.

Please include automated tests. Including tests in your pull request is one way to help your patch be considered faster. To learn about WordPress' test suites, visit the Automated Testing page in the handbook.

If you have not had a chance, please review the Contribute with Code page in the WordPress Core Handbook.

The Developer Hub also documents the various coding standards that are followed:

Thank you,
The WordPress Project

@github-actions

github-actions Bot commented Jun 19, 2026

Copy link
Copy Markdown

The following accounts have interacted with this PR and/or linked issues. I will continue to update these lists as activity occurs. You can also manually ask me to refresh this list by adding the props-bot label.

Core Committers: Use this line as a base for the props when committing in SVN:

Props bor0, peterwilsoncc, dmsnell.

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.

@github-actions

Copy link
Copy Markdown

Test using WordPress Playground

The changes in this pull request can previewed and tested using a WordPress Playground instance.

WordPress Playground is an experimental project that creates a full WordPress instance entirely within the browser.

Some things to be aware of

  • All changes will be lost when closing a tab with a Playground instance.
  • All changes will be lost when refreshing the page.
  • A fresh instance is created each time the link below is clicked.
  • Every time this pull request is updated, a new ZIP file containing all changes is created. If changes are not reflected in the Playground instance,
    it's possible that the most recent build failed, or has not completed. Check the list of workflow runs to be sure.

For more details about these limitations and more, check out the Limitations page in the WordPress Playground documentation.

Test this pull request with WordPress Playground.

bor0 and others added 3 commits June 19, 2026 18:17
- Multi-item associative arrays: each value on its own line
- Space after function keyword in anonymous/arrow functions
- Inline closure expanded to multi-line (brace must be last content on line)

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Replaces the phpass approach with HMAC-SHA256 per feedback from @dmsnell
in comment:29.

Instead of storing timestamp:phpass_hash and requiring signup_id as a
second lookup parameter, we now:

- Build a triplet: user_email:timestamp:random_key
- Store base64(HMAC-SHA256(triplet, AUTH_KEY+AUTH_SALT)) in the DB (44
  chars, fits the existing varchar(50) column)
- Send base64url(triplet) as the activation URL parameter

On activation the triplet is decoded from the URL, the HMAC is
recomputed, and the row is found with a direct indexed lookup:
WHERE user_email = %s AND activation_key = %s

This eliminates signup_id from URLs entirely. Legacy plain-text keys
(pre-upgrade pending activations) continue to work via a fallback
WHERE activation_key = %s path.

Props bor0, dmsnell, tomdxw, jeremyfelt, SergeyBiryukov, SirLouen.
Fixes #38474.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

During the introduction of bcrypt, a gotcha was discovered for sites that don't update the user tables (wordpress.org being one such site). The activation key meta needs to be under 60 characters to ensure that the full data is stored in the legacy table structure.

I recommend adding some tests for this to this file, you can see an example of how it was tested for the bcrypt implementation in this code sample:

/**
* Ensure the hash of the user activation key remains less than 60 characters in length to account for the old users table schema.
*
* @ticket 21022
*/
public function test_user_activation_key_against_old_users_table_schema() {
// Mimic the schema of the users table prior to WordPress 4.4.
add_filter( 'wp_pre_insert_user_data', array( $this, 'mimic_users_schema_prior_to_44' ) );
$username = 'old-schema-user';
// Create a user.
$user_id = $this->factory()->user->create(
array(
'user_login' => $username,
'user_email' => 'old-schema-user@example.com',
)
);
$user = get_userdata( $user_id );
$key = get_password_reset_key( $user );
// A correctly saved key should be accepted.
$check = check_password_reset_key( $key, $user->user_login );
$this->assertNotWPError( $check );
$this->assertInstanceOf( 'WP_User', $check );
$this->assertSame( $user->ID, $check->ID );
$this->assertNotSame( self::$user_id, $user->ID, 'A unique user must be created for this test, the shared fixture must not be used' );
}
/*
* Fake the schema of the users table prior to WordPress 4.4 to mimic sites that are using the
* `DO_NOT_UPGRADE_GLOBAL_TABLES` constant and have not updated the users table schema.
*
* The schema of the wp_users table on wordpress.org has not been updated since the schema was changed in [35638]
* for WordPress 4.4, which means the `user_activation_key` field remains at 60 characters length and the `user_pass`
* field remains at 64 characters length instead of the expected 255. Although this is unlikely to affect other
* sites, this can be accommodated for in the codebase.
*
* Actually altering the database schema during tests will commit the transaction and break subsequent tests, hence
* the use of this filter.
*/
public function mimic_users_schema_prior_to_44( array $data ): array {
if ( isset( $data['user_pass'] ) ) {
$this->assertLessThanOrEqual( 64, strlen( $data['user_pass'] ) );
}
if ( isset( $data['user_activation_key'] ) ) {
$this->assertLessThanOrEqual( 60, strlen( $data['user_activation_key'] ) );
}
return $data;
}

Comment thread src/wp-includes/ms-functions.php Outdated

$key = substr( md5( time() . wp_rand() . $domain ), 0, 16 );
$key = substr( md5( time() . wp_rand() . $domain ), 0, 16 );
$timestamp = time();

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just a nit: but it would probably be more ideal to use the same time() value throughout here. it may not matter, especially if we are treating the key as random bytes.

on that note, I wonder if we would want to opportunistically use random_bytes() where available.

Comment thread src/wp-includes/ms-functions.php Outdated
$timestamp = time();
$triplet = $user_email . ':' . $timestamp . ':' . $key;
$payload = rtrim( strtr( base64_encode( $triplet ), '+/', '-_' ), '=' );
$hash = base64_encode( hash_hmac( 'sha256', $triplet, wp_salt( 'auth' ), true ) );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we seem to be building a web-safe base64-encoding of the $payload but not here. is there value in generating them identically?

Comment thread src/wp-includes/ms-functions.php Outdated
$timestamp = time();
$triplet = $user_email . ':' . $timestamp . ':' . $key;
$payload = rtrim( strtr( base64_encode( $triplet ), '+/', '-_' ), '=' );
$hash = base64_encode( hash_hmac( 'sha256', $triplet, wp_salt( 'auth' ), true ) );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

when it was just a random key being generated, it seemed less of an issue to duplicate, but due to the sensitivity and particularity of this code, I wonder if it wouldn’t be best to abstract it into a single place.

function _wp_generate_signup_key( string $email ) {
	…

	return [ 'email_key' => $payload, 'activation_key' => $hash ];
}

if ( time() > ( (int) $timestamp + $expiration_duration ) ) {
return new WP_Error( 'expired_key', __( 'Invalid key' ) );
}
} else {

@dmsnell dmsnell Jun 23, 2026

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we might want to apply stricter parsing of the legacy key to avoid ambiguity here.

// Check also for non-expired legacy MD5 activation keys.
if ( 1 === preg_match( '~[0-9a-f]{16}~i', $key ) ) {
	…
}

bor0 and others added 2 commits June 23, 2026 23:55
- Extract `_wp_generate_signup_key()` helper to deduplicate the
  triplet/payload/hash logic shared between `wpmu_signup_blog()` and
  `wpmu_signup_user()`. Uses `random_bytes()` where available for
  better entropy, and a single `time()` call throughout.
- Tighten legacy key detection: `preg_match('~^[0-9a-f]{16}$~', $key)`
  explicitly matches the original MD5-substr format instead of falling
  through a broad else branch.
- Add test asserting the stored activation key is ≤ 60 chars for
  compatibility with legacy table schemas (e.g. DO_NOT_UPGRADE_GLOBAL_TABLES).
- Fix legacy key test fixtures to use valid 16-char hex keys.

Props peterwilsoncc, dmsnell.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
@bor0

bor0 commented Jun 23, 2026

Copy link
Copy Markdown
Member Author

Thanks @dmsnell, @peterwilsoncc - addressed your comments, lmk how this looks! 🙇‍♂️

Comment thread src/wp-includes/ms-functions.php Outdated
// New HMAC format.
list( $email, $timestamp, $random ) = $parts;

$expected_hash = base64_encode( hash_hmac( 'sha256', $decoded, wp_salt( 'auth' ), true ) );

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I find the generate/verify pairing helpful. thank you already for creating _wp_generate_signup_key(). what would you think about a _wp_signup_key_from_email( $key ) which would return the expected hash or null?

there must be a better name for this, as we now have two kinds of keys: the activation_key already stored in the database, and the email key, a digest of it.

so maybe _wp_generate_signup_digest() and _wp_activation_key_from_digest()? or something along those lines?

I think that this function could do double-duty of returning the activation key if the digest parses and indicating if it’s not a valid digest, making the containing if simpler

$activation_key = _wp_activation_key_from_signup_digest( $key );

if ( isset( $activation_key ) ) {
	…
} else {
	return new EP_Error( 'invalid_key', __( 'Invalid or unknown activation key.' );
}

actually in this light I think we could have the _wp_activation_key_from_signup_link() function parse new and legacy formats, if the output is ?activation_key because the remaining code doesn’t care what kind of key it was in the email link.

// Legacy plain-text 16-char hex key — allow for BC with pre-upgrade pending activations.
$signup = $wpdb->get_row(
$wpdb->prepare( "SELECT * FROM $wpdb->signups WHERE activation_key = %s", $key )
);

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this is a note for here and for line 1283 above with the expiration check.

in the case of the new key format we should have a cryptographically secure way to trust the provided timestamp, however, for legacy keys it looks like we aren’t applying any expiration rules, even though we should have the same $timestamp in the registered column.

in wpmu_validate_user_signup() this value is checked, so maybe it doesn’t matter, but if so, we are potentially leaking information by returning in the one case and not in the other (because the new key expiration will be immediately checked while the legacy key relies on a DB round-trip).

this could be worth keeping out of this ticket, but I would expect to embed the expiration into the database query.

SELECT * FROM $wpdb->signups WHERE activation_key = %s AND registered >= %s

and we would supply the appropriate expiration date in there. (another side note, but it appears that wpmu_validate_user_signup() hard-codes two days for expiration while this code allows extension through 'activate_signup_expiration'

bor0 and others added 2 commits June 25, 2026 09:49
- Extract _wp_resolve_signup_key() to pair with _wp_generate_signup_key(),
  handling both new HMAC and legacy hex formats per @dmsnell's suggestion.
- Apply expiration check to legacy keys via $signup->registered, eliminating
  the asymmetric behaviour flagged by @dmsnell.
- Add docblock note to _wp_generate_signup_key() about salt rotation
  invalidating pending activations.
- Add PHPUnit test for expired legacy key rejection.

Props dmsnell.

Co-Authored-By: Claude Sonnet 4.6 (1M context) <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants