WordPress secrets and credentials audit
A focused review for the secrets layer — what's stored, how it's
generated, how it's compared, how it leaks. Narrow scope by design;
run alongside wp-security-audit and wp-security-deep.
When to use this skill
Trigger when:
- Reviewing auth, registration, password reset, or 2FA flows.
- The plugin integrates a third-party API (Stripe, SendGrid, OpenAI,
GitHub etc.) — look for stored credentials.
- The user asks "is my API key safe", "how should I store this token".
- Before wp.org submission (hardcoded secrets are a guaranteed reject).
- The diff contains:
rand, mt_rand, uniqid, md5, sha1,
password_hash, password_verify, setcookie,
wp_generate_password, random_bytes, random_int, openssl_random_pseudo_bytes,
update_option.*api_key, update_option.*secret,
define.*KEY, define.*SECRET.
Audit checks
1. Hardcoded credentials in source
// HIGH — anyone with repo read access has prod credentials
const STRIPE_SECRET = 'sk_live_4eC39HqLyjWDarjtT1...';
$api_key = 'AIzaSy...';
define( 'MYPLUGIN_API_TOKEN', 'ghp_xxx...' );
Fix: load from wp-config.php constants (server-deployed, not
in repo), an option (get_option) with admin-only write, or an env
var via getenv(). Provide a settings page for the user to enter
their own.
Search patterns:
- String literals matching common key prefixes:
sk_, pk_live_,
AKIA, ghp_, xoxb-, AIza, Bearer , eyJ (JWT),
hex strings 32+ chars.
define( '...KEY...', define( '...SECRET...', define( '...TOKEN...'
with a non-empty literal.
- Long base64 strings in source (
[A-Za-z0-9+/]{40,}={0,2}).
Flag any hit. Even "test" keys count — they get committed to prod.
2. Weak randomness for security tokens
// HIGH — predictable
$token = md5( uniqid() );
$reset_key = mt_rand();
$session_id = uniqid( '', true );
rand, mt_rand, uniqid are NOT cryptographically secure. They're
seeded predictably and the output can be reconstructed.
Fix — use one of:
// WP-native, seeded from random_bytes internally
$token = wp_generate_password( 32, false ); // alnum
$token = wp_generate_password( 64, true, true ); // alnum + special
// PHP-native
$token = bin2hex( random_bytes( 32 ) ); // 64 hex chars
$num = random_int( 100000, 999999 ); // 6-digit OTP
// WP nonce (for CSRF only — not a long-lived token!)
$nonce = wp_create_nonce( 'action' );
Don't confuse:
wp_create_nonce is a 10-char CSRF token, valid 12-24h. NOT for
password resets, API keys, session IDs.
wp_generate_uuid4() is NOT cryptographically random despite the
v4 UUID name. WordPress core implements it with mt_rand()
(verified in wp-includes/functions.php). Use it for non-security
identifiers (post UIDs, log IDs) only. For security tokens use
wp_generate_password(), random_bytes(), or random_int().
3. Password storage
// HIGH — broken
$hash = md5( $password );
$hash = sha1( $password . SALT );
$hash = crypt( $password ); // weak default algo
WordPress provides wp_hash_password() / wp_check_password() —
use these for WP user accounts. Since WP 6.8 the default algorithm
is bcrypt (was PHPass / portable hash before). To work around bcrypt's
72-byte input limit, WP first HMAC-SHA384 pre-hashes the password,
base64-encodes the result, then runs password_hash() with
PASSWORD_BCRYPT, prefixing the output with $wp to distinguish it
from vanilla bcrypt. wp_check_password() still verifies legacy
PHPass hashes from older sites and rehashes on successful login, so
the migration is transparent — don't reimplement password storage
for WP users, always go through these functions.
The algorithm and options are filterable (wp_hash_password_algorithm,
wp_hash_password_options) for sites that want argon2id or stronger
bcrypt cost — but a plugin should not change site-wide defaults unless
explicitly asked.
For non-WP-user passwords (custom auth, API client secrets):
$hash = password_hash( $password, PASSWORD_DEFAULT );
// later
if ( password_verify( $input, $hash ) ) { /* ok */ }
if ( password_needs_rehash( $hash, PASSWORD_DEFAULT ) ) {
// rehash and update store
}
PASSWORD_DEFAULT resolves to bcrypt across all currently shipped PHP
versions and may change in a future major PHP release — that's the
point of the constant. Always pair it with password_needs_rehash()
on verification to migrate stored hashes when the algorithm changes.
Allocate at least 255 bytes for the stored hash column to leave room
for future algorithm output growth. Never roll your own with hash()
4. Cookie flags
// MEDIUM/HIGH — readable by JS, sent over HTTP, sent cross-site
setcookie( 'session', $token, time() + 3600 );
Fix:
setcookie( 'myplugin_session', $token, [
'expires' => time() + 3600,
'path' => COOKIEPATH ?: '/',
'domain' => COOKIE_DOMAIN ?: '',
'secure' => is_ssl(),
'httponly' => true,
'samesite' => 'Lax', // or 'Strict' for sensitive flows
] );
For WP's own auth, don't roll your own — use wp_set_auth_cookie
which handles all flags correctly.
Flag: any setcookie storing a token, session ID, or user identifier
without secure (when is_ssl()) and httponly.
5. Secrets in logs and debug output
// MEDIUM — secrets in error_log, often shipped to log aggregators
error_log( 'API request: ' . print_r( $request, true ) ); // includes auth header
var_dump( $_SERVER ); // HTTP_AUTHORIZATION leaks
WP_CLI::log( "Token: $token" );
Flag:
error_log, var_dump, print_r, var_export over variables
named *token*, *key*, *secret*, *password*, *auth*,
$_SERVER, full request bodies, or response objects with auth
headers.
WP_DEBUG_LOG enabled in production code path (not a check, but
warn if define( 'WP_DEBUG_LOG', true ) appears in plugin code —
shouldn't be set by a plugin).
Fix: redact before logging:
$safe = $request;
unset( $safe['headers']['Authorization'] );
$safe['body'] = '<redacted>';
error_log( wp_json_encode( $safe ) );
6. Storing API keys: option vs constant
Both are common — guidance:
- Constant in
wp-config.php: best for site-owner-managed,
rarely-changed secrets. Not in DB, not in repo, only readable by
PHP. Document this in plugin readme.
- Option (
update_option): needed when the plugin offers a
settings page. Acceptable, but:
- Mark the option
autoload = false if not needed every request.
- Restrict the setting page to
manage_options.
- Don't
wp_send_json or echo the option value back to non-admins.
- User meta: only for per-user tokens (e.g. user's own GitHub
PAT). Never for site-wide secrets.
Flag: site-wide secrets stored in user meta, or settings pages
without a capability check.
7. Token comparison
Cross-reference with wp-security-deep check #8: any secret
comparison must use hash_equals( $stored, (string) $given ). Never
== or ===.
Severity guide
- HIGH: hardcoded secret in source, weak randomness for password
reset / session token, password stored with md5/sha1, missing
HttpOnly on session cookie.
- MEDIUM: secrets logged, cookie missing SameSite, weak randomness
for non-secret IDs that gain meaning later.
- LOW: API key in option without
autoload = false, no rotation
story documented.
Report format
Same as wp-security-audit. If hardcoded secrets are found, the
report MUST include a top-line warning recommending:
- Revoke the leaked credential at the issuing service immediately.
- Rotate to a new secret.
- Rewrite git history to remove the secret (
git filter-repo or
BFG) — or accept that the secret is permanently compromised in
the repo.
- Move to
wp-config.php constant or settings option.
State this even when the user only asked for a code review — leaked
secrets need real-world action, not just a code change.
Cross-references
wp-security-audit: basic sanitize/escape/nonce/capability.
wp-security-deep: object injection, SSRF, CSRF on GET, mass
assignment, file include, mail/zip injection, type juggling, race.
What this skill does NOT cover
- Cryptographic protocol design (key derivation, signing schemes,
envelope encryption).
- Secret scanning of git history (use
gitleaks, trufflehog).
- Secret rotation processes / KMS integrations.
- Hardware token / 2FA flow correctness beyond storage.
References
1---2name: wp-security-secrets3description: Audits WordPress plugin/theme code for secret-handling and4 credential issues — hardcoded API keys, DB credentials, or signing5 secrets in source; weak randomness (rand, mt_rand, uniqid) used for6 security tokens, password reset links, nonces, or session IDs;7 password storage with md5/sha1/crypt instead of password_hash;8 insecure cookie flags (missing Secure, HttpOnly, SameSite) on9 sensitive cookies; secrets logged via error_log / var_dump in10 production code paths. Use before plugin release, when reviewing11 auth/registration/login features, when integrating third-party12 APIs, or when the user mentions "API key", "token", "session",13 "password reset".14author: Soczó Kristóf15contact: mailto:lonsdale201@hotmail.com16plugin: wordpress17plugin-version-tested: "6.0 - 6.9"18php-min: "7.4"19last-updated: "2026-04-28"20docs:21 - https://www.php.net/manual/en/function.password-hash.php22 - https://www.php.net/manual/en/function.random-bytes.php23 - https://developer.wordpress.org/reference/functions/wp_generate_password/24metadata:25 source: https://skillmd.com/skills/vikingokft/wp-security-secrets26---2728# WordPress secrets and credentials audit2930A focused review for the secrets layer — what's stored, how it's31generated, how it's compared, how it leaks. Narrow scope by design;32run alongside `wp-security-audit` and `wp-security-deep`.3334## When to use this skill3536Trigger when:3738- Reviewing auth, registration, password reset, or 2FA flows.39- The plugin integrates a third-party API (Stripe, SendGrid, OpenAI,40 GitHub etc.) — look for stored credentials.41- The user asks "is my API key safe", "how should I store this token".42- Before wp.org submission (hardcoded secrets are a guaranteed reject).43- The diff contains: `rand`, `mt_rand`, `uniqid`, `md5`, `sha1`,44 `password_hash`, `password_verify`, `setcookie`,45 `wp_generate_password`, `random_bytes`, `random_int`, `openssl_random_pseudo_bytes`,46 `update_option.*api_key`, `update_option.*secret`,47 `define.*KEY`, `define.*SECRET`.4849## Audit checks5051### 1. Hardcoded credentials in source5253```php54// HIGH — anyone with repo read access has prod credentials55const STRIPE_SECRET = 'sk_live_4eC39HqLyjWDarjtT1...';56$api_key = 'AIzaSy...';57define( 'MYPLUGIN_API_TOKEN', 'ghp_xxx...' );58```5960**Fix:** load from `wp-config.php` constants (server-deployed, not61in repo), an option (`get_option`) with admin-only write, or an env62var via `getenv()`. Provide a settings page for the user to enter63their own.6465Search patterns:66- String literals matching common key prefixes: `sk_`, `pk_live_`,67 `AKIA`, `ghp_`, `xoxb-`, `AIza`, `Bearer `, `eyJ` (JWT),68 hex strings 32+ chars.69- `define( '...KEY...'`, `define( '...SECRET...'`, `define( '...TOKEN...'`70 with a non-empty literal.71- Long base64 strings in source (`[A-Za-z0-9+/]{40,}={0,2}`).7273Flag any hit. Even "test" keys count — they get committed to prod.7475### 2. Weak randomness for security tokens7677```php78// HIGH — predictable79$token = md5( uniqid() );80$reset_key = mt_rand();81$session_id = uniqid( '', true );82```8384`rand`, `mt_rand`, `uniqid` are NOT cryptographically secure. They're85seeded predictably and the output can be reconstructed.8687**Fix — use one of:**8889```php90// WP-native, seeded from random_bytes internally91$token = wp_generate_password( 32, false ); // alnum92$token = wp_generate_password( 64, true, true ); // alnum + special9394// PHP-native95$token = bin2hex( random_bytes( 32 ) ); // 64 hex chars96$num = random_int( 100000, 999999 ); // 6-digit OTP9798// WP nonce (for CSRF only — not a long-lived token!)99$nonce = wp_create_nonce( 'action' );100```101102**Don't confuse:**103- `wp_create_nonce` is a 10-char CSRF token, valid 12-24h. NOT for104 password resets, API keys, session IDs.105- `wp_generate_uuid4()` is **NOT cryptographically random** despite the106 v4 UUID name. WordPress core implements it with `mt_rand()`107 (verified in `wp-includes/functions.php`). Use it for non-security108 identifiers (post UIDs, log IDs) only. For security tokens use109 `wp_generate_password()`, `random_bytes()`, or `random_int()`.110111### 3. Password storage112113```php114// HIGH — broken115$hash = md5( $password );116$hash = sha1( $password . SALT );117$hash = crypt( $password ); // weak default algo118```119120WordPress provides `wp_hash_password()` / `wp_check_password()` —121use these for WP user accounts. **Since WP 6.8** the default algorithm122is bcrypt (was PHPass / portable hash before). To work around bcrypt's12372-byte input limit, WP first HMAC-SHA384 pre-hashes the password,124base64-encodes the result, then runs `password_hash()` with125`PASSWORD_BCRYPT`, prefixing the output with `$wp` to distinguish it126from vanilla bcrypt. `wp_check_password()` still verifies legacy127PHPass hashes from older sites and rehashes on successful login, so128the migration is transparent — **don't reimplement password storage129for WP users**, always go through these functions.130131The algorithm and options are filterable (`wp_hash_password_algorithm`,132`wp_hash_password_options`) for sites that want argon2id or stronger133bcrypt cost — but a plugin should not change site-wide defaults unless134explicitly asked.135136For non-WP-user passwords (custom auth, API client secrets):137138```php139$hash = password_hash( $password, PASSWORD_DEFAULT );140// later141if ( password_verify( $input, $hash ) ) { /* ok */ }142if ( password_needs_rehash( $hash, PASSWORD_DEFAULT ) ) {143 // rehash and update store144}145```146147`PASSWORD_DEFAULT` resolves to bcrypt across all currently shipped PHP148versions and may change in a future major PHP release — that's the149point of the constant. Always pair it with `password_needs_rehash()`150on verification to migrate stored hashes when the algorithm changes.151Allocate at least 255 bytes for the stored hash column to leave room152for future algorithm output growth. Never roll your own with `hash()`153+ `salt`.154155### 4. Cookie flags156157```php158// MEDIUM/HIGH — readable by JS, sent over HTTP, sent cross-site159setcookie( 'session', $token, time() + 3600 );160```161162**Fix:**163164```php165setcookie( 'myplugin_session', $token, [166 'expires' => time() + 3600,167 'path' => COOKIEPATH ?: '/',168 'domain' => COOKIE_DOMAIN ?: '',169 'secure' => is_ssl(),170 'httponly' => true,171 'samesite' => 'Lax', // or 'Strict' for sensitive flows172] );173```174175For WP's own auth, **don't roll your own** — use `wp_set_auth_cookie`176which handles all flags correctly.177178Flag: any `setcookie` storing a token, session ID, or user identifier179without `secure` (when `is_ssl()`) and `httponly`.180181### 5. Secrets in logs and debug output182183```php184// MEDIUM — secrets in error_log, often shipped to log aggregators185error_log( 'API request: ' . print_r( $request, true ) ); // includes auth header186var_dump( $_SERVER ); // HTTP_AUTHORIZATION leaks187WP_CLI::log( "Token: $token" );188```189190Flag:191- `error_log`, `var_dump`, `print_r`, `var_export` over variables192 named `*token*`, `*key*`, `*secret*`, `*password*`, `*auth*`,193 `$_SERVER`, full request bodies, or response objects with auth194 headers.195- `WP_DEBUG_LOG` enabled in production code path (not a check, but196 warn if `define( 'WP_DEBUG_LOG', true )` appears in plugin code —197 shouldn't be set by a plugin).198199**Fix:** redact before logging:200201```php202$safe = $request;203unset( $safe['headers']['Authorization'] );204$safe['body'] = '<redacted>';205error_log( wp_json_encode( $safe ) );206```207208### 6. Storing API keys: option vs constant209210Both are common — guidance:211212- **Constant in `wp-config.php`**: best for site-owner-managed,213 rarely-changed secrets. Not in DB, not in repo, only readable by214 PHP. Document this in plugin readme.215- **Option (`update_option`)**: needed when the plugin offers a216 settings page. Acceptable, but:217 - Mark the option `autoload = false` if not needed every request.218 - Restrict the setting page to `manage_options`.219 - Don't `wp_send_json` or echo the option value back to non-admins.220- **User meta**: only for per-user tokens (e.g. user's own GitHub221 PAT). Never for site-wide secrets.222223Flag: site-wide secrets stored in user meta, or settings pages224without a capability check.225226### 7. Token comparison227228Cross-reference with `wp-security-deep` check #8: any secret229comparison must use `hash_equals( $stored, (string) $given )`. Never230`==` or `===`.231232## Severity guide233234- **HIGH:** hardcoded secret in source, weak randomness for password235 reset / session token, password stored with md5/sha1, missing236 HttpOnly on session cookie.237- **MEDIUM:** secrets logged, cookie missing SameSite, weak randomness238 for non-secret IDs that gain meaning later.239- **LOW:** API key in option without `autoload = false`, no rotation240 story documented.241242## Report format243244Same as `wp-security-audit`. If hardcoded secrets are found, the245report MUST include a top-line warning recommending:2462471. Revoke the leaked credential at the issuing service immediately.2482. Rotate to a new secret.2493. Rewrite git history to remove the secret (`git filter-repo` or250 BFG) — or accept that the secret is permanently compromised in251 the repo.2524. Move to `wp-config.php` constant or settings option.253254State this even when the user only asked for a code review — leaked255secrets need real-world action, not just a code change.256257## Cross-references258259- **`wp-security-audit`**: basic sanitize/escape/nonce/capability.260- **`wp-security-deep`**: object injection, SSRF, CSRF on GET, mass261 assignment, file include, mail/zip injection, type juggling, race.262263## What this skill does NOT cover264265- Cryptographic protocol design (key derivation, signing schemes,266 envelope encryption).267- Secret scanning of git history (use `gitleaks`, `trufflehog`).268- Secret rotation processes / KMS integrations.269- Hardware token / 2FA flow correctness beyond storage.270271## References272273- PHP password hashing:274 https://www.php.net/manual/en/function.password-hash.php275- `random_bytes`:276 https://www.php.net/manual/en/function.random-bytes.php277- `wp_generate_password`:278 https://developer.wordpress.org/reference/functions/wp_generate_password/279- OWASP secret management:280 https://cheatsheetseries.owasp.org/cheatsheets/Secrets_Management_Cheat_Sheet.html