diff --git a/source/extensions/filters/http/oauth2/filter.cc b/source/extensions/filters/http/oauth2/filter.cc index 51c6af49c4e..63b7409b7ae 100644 --- a/source/extensions/filters/http/oauth2/filter.cc +++ b/source/extensions/filters/http/oauth2/filter.cc @@ -826,15 +826,26 @@ std::string OAuth2Filter::decryptToken(const std::string& encrypted_token) const } DecryptResult decrypt_result = decrypt(encrypted_token, config_->hmacSecret()); - if (decrypt_result.error.has_value()) { - ENVOY_LOG(error, "failed to decrypt token: {}, error: {}", encrypted_token, - decrypt_result.error.value()); + + // Decryption can spuriously succeed against a token that was either never encrypted, or was + // encrypted under a different secret — PKCS#7 padding is valid by chance with probability + // ~1/256, leaving us with arbitrary binary bytes that would later fail HeaderString validation + // when written back into the Cookie header. Treat any plaintext that is not a valid header value + // as a decrypt failure and fall through to the legacy/wrong-secret behavior below. + const bool decrypt_failed = decrypt_result.error.has_value() || + !Http::HeaderUtility::headerValueIsValid(decrypt_result.plaintext); + + if (decrypt_failed) { + ENVOY_STREAM_LOG(error, "failed to decrypt token: {}, error: {}", *decoder_callbacks_, + encrypted_token, + decrypt_result.error.value_or("plaintext is not a valid header value")); // There are two cases: // 1. The token is a legacy unencrypted token. // In this case, we return the token as-is to allow the request to proceed. - // 2. The token is encrypted, but the decryption failed due to the HMAC secret is changed. - // In this case, we return the original encrypted token, the HMAC validation will fail - // and the user will be redirected to the OAuth server for re-authentication. + // 2. The token is encrypted, but the decryption failed (or produced invalid plaintext) due to + // the HMAC secret being changed. In this case, we return the original encrypted token; the HMAC + // validation will fail and the user will be redirected to the OAuth server for + // re-authentication. return encrypted_token; } return decrypt_result.plaintext; diff --git a/tools/spelling/spelling_dictionary.txt b/tools/spelling/spelling_dictionary.txt index d8ce66a8ad7..c9dbec79a71 100644 --- a/tools/spelling/spelling_dictionary.txt +++ b/tools/spelling/spelling_dictionary.txt @@ -92,6 +92,7 @@ ETX FS FIXME decrypted +decrypts gperf HEXDIG HEXDIGIT @@ -371,6 +372,7 @@ PERF PGV PID PKCE +PKCS PKCS12 PKTINFO PNG