Repository navigation
fix(auth): verify workload cert and key match, retrying mid-rotation reads #19043
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
e0c26de
9ecc655
37620f3
9a53c39
b79e78d
c1373a5
fcff526
9f6a0ef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,7 @@ | |
| """Helper functions for getting mTLS cert and key.""" | ||
|
|
||
| import contextlib | ||
| import inspect | ||
| import json | ||
| import logging | ||
| import os | ||
|
|
@@ -28,6 +29,10 @@ | |
| from typing import Generator, List, Optional, Tuple, Union, cast | ||
| from urllib.parse import urlsplit | ||
|
|
||
| from cryptography import x509 | ||
| from cryptography.exceptions import UnsupportedAlgorithm | ||
| from cryptography.hazmat.primitives import serialization | ||
|
|
||
| from google.auth import _agent_identity_utils, _cloud_sdk, environment_vars, exceptions | ||
|
|
||
| CONTEXT_AWARE_METADATA_PATH = "~/.secureConnect/context_aware_metadata.json" | ||
|
|
@@ -52,6 +57,11 @@ | |
|
|
||
| _LOGGER = logging.getLogger(__name__) | ||
|
|
||
| # Separate cert and key files are read up to 3 times, 100ms apart, to ride out | ||
| # mid-rotation updates where a file is briefly missing or incomplete or the pair | ||
| # does not yet match. | ||
| _CERT_KEY_MATCH_MAX_ATTEMPTS = 3 | ||
| _CERT_KEY_MATCH_RETRY_INTERVAL = 0.1 | ||
|
|
||
| _PASSPHRASE_REGEX = re.compile( | ||
| b"-----BEGIN PASSPHRASE-----(.+)-----END PASSPHRASE-----", re.DOTALL | ||
|
|
@@ -164,9 +174,6 @@ def _encrypt_key_if_plaintext( | |
| """ | ||
| import secrets | ||
|
|
||
| import cryptography | ||
| from cryptography.hazmat.primitives import serialization | ||
|
|
||
| try: | ||
| pkey = serialization.load_pem_private_key(key_bytes, password=None) | ||
| # It's plaintext, encrypt it. | ||
|
|
@@ -184,7 +191,7 @@ def _encrypt_key_if_plaintext( | |
| ), | ||
| ) | ||
| return encrypted_content, target_passphrase | ||
| except (ValueError, TypeError, cryptography.exceptions.UnsupportedAlgorithm): | ||
| except (ValueError, TypeError, UnsupportedAlgorithm): | ||
| # Likely already encrypted, invalid, or unsupported algorithm, return as-is. | ||
| return key_bytes, passphrase | ||
|
|
||
|
|
@@ -698,10 +705,99 @@ def _read_credential_bundle_file(bundle_path): | |
|
|
||
|
|
||
| def _read_cert_and_key_files(cert_path, key_path): | ||
| cert_data = _read_cert_file(cert_path) | ||
| key_data = _read_key_file(key_path) | ||
| """Reads the certificate chain and private key from separate files. | ||
|
|
||
| return cert_data, key_data | ||
| A rotation on disk can briefly leave a file missing or incomplete, or one | ||
| file updated before the other, so both files are retried if a file read, | ||
| PEM extraction, or the public-key match check fails. | ||
|
|
||
| Args: | ||
| cert_path (str): The certificate chain file path. | ||
| key_path (str): The private key file path. | ||
|
|
||
| Returns: | ||
| Tuple[bytes, bytes]: The certificate chain and private key bytes in | ||
| PEM format. | ||
|
|
||
| Raises: | ||
| OSError: If either file still cannot be read after all attempts. | ||
| google.auth.exceptions.ClientCertError: If either file is still not in | ||
| a valid PEM format, or the private key still does not match the | ||
| certificate, after all attempts. | ||
| """ | ||
| for attempt in range(_CERT_KEY_MATCH_MAX_ATTEMPTS): | ||
| if attempt: | ||
| time.sleep(_CERT_KEY_MATCH_RETRY_INTERVAL) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. On a 401,
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. In |
||
| try: | ||
| cert_data = _read_cert_file(cert_path) | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. When |
||
| key_data = _read_key_file(key_path) | ||
| except (OSError, exceptions.ClientCertError) as exc: | ||
| _LOGGER.debug( | ||
| "Failed to read certificate %s or private key %s (attempt %d of %d): %s", | ||
| cert_path, | ||
| key_path, | ||
| attempt + 1, | ||
| _CERT_KEY_MATCH_MAX_ATTEMPTS, | ||
| exc, | ||
| ) | ||
| if attempt + 1 == _CERT_KEY_MATCH_MAX_ATTEMPTS: | ||
| raise | ||
| continue | ||
| if not _has_cert_key_mismatch(cert_data, key_data): | ||
| return cert_data, key_data | ||
| _LOGGER.debug( | ||
| "Private key %s does not match certificate %s (attempt %d of %d)", | ||
| key_path, | ||
| cert_path, | ||
| attempt + 1, | ||
| _CERT_KEY_MATCH_MAX_ATTEMPTS, | ||
| ) | ||
|
|
||
| raise exceptions.ClientCertError( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. One wrinkle on the 401 trade-off from the earlier review. If the cert file updates to a new cert before the key file catches up and the mismatch lasts past 200ms, catching |
||
| "Certificate {} and private key {} do not match after {} attempts".format( | ||
| cert_path, key_path, _CERT_KEY_MATCH_MAX_ATTEMPTS | ||
| ) | ||
| ) | ||
|
|
||
|
|
||
| def _get_key_match_load_kwargs(): | ||
| # Only the public half is compared, so skip RSA private-key validation | ||
| # where supported (cryptography >= 39.0.0); it is slow and the TLS layer | ||
| # does not perform it either. | ||
| try: | ||
| if ( | ||
| "unsafe_skip_rsa_key_validation" | ||
| in inspect.signature(serialization.load_pem_private_key).parameters | ||
| ): | ||
| return {"unsafe_skip_rsa_key_validation": True} | ||
| except (TypeError, ValueError): | ||
| pass | ||
| return {} | ||
|
|
||
|
|
||
| _KEY_MATCH_LOAD_KWARGS = _get_key_match_load_kwargs() | ||
|
|
||
|
|
||
| def _has_cert_key_mismatch(cert_chain, key): | ||
| """Checks whether the private key does not belong to the leaf certificate. | ||
|
|
||
| Returns False when either value cannot be parsed (for example, a | ||
| passphrase-encrypted key) because no mismatch can be detected, leaving | ||
| validation to the TLS layer as before. | ||
| """ | ||
| try: | ||
| cert_public_key = x509.load_pem_x509_certificate(cert_chain).public_key() | ||
| key_public_key = serialization.load_pem_private_key( | ||
| key, password=None, **_KEY_MATCH_LOAD_KWARGS | ||
| ).public_key() | ||
|
Comment on lines
+790
to
+792
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This loads the private key with full RSA validation on every call of Cost (cryptography 46.0.7, OpenSSL 3.6.5, per check): RSA-2048 ~41 ms, RSA-4096 ~286 ms, EC P-256 ~0.06 ms. Agent-identity pools are fixed to ECDSA P-256, but RSA keys are documented for this path: the X.509 Workload Identity Federation setup guide generates Not a gate: if validation fails, the Since only the public half is compared, suggest skipping the validation where the installed library supports it (needs # Only the key's public half is compared, so skip RSA private-key validation
# where supported: it is slow (~40 ms for RSA-2048) and the TLS layer does not
# perform it either.
try:
_SKIP_RSA_VALIDATION_SUPPORTED = (
"unsafe_skip_rsa_key_validation"
in inspect.signature(serialization.load_pem_private_key).parameters
)
except (TypeError, ValueError):
_SKIP_RSA_VALIDATION_SUPPORTED = False
_KEY_MATCH_LOAD_KWARGS = (
{"unsafe_skip_rsa_key_validation": True} if _SKIP_RSA_VALIDATION_SUPPORTED else {}
)
...
key_public_key = serialization.load_pem_private_key(
key, password=None, **_KEY_MATCH_LOAD_KWARGS
).public_key()I applied this to a copy of the branch:
The
Contributor
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Done. Put the signature check in a small helper so the older-version and missing-signature fallbacks can be unit-tested directly without reloading the module, and added a test for the corrupted-RSA mismatch case. |
||
| except (ValueError, TypeError, UnsupportedAlgorithm, x509.InvalidVersion): | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: |
||
| return False | ||
|
|
||
| return cert_public_key.public_bytes( | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nit: |
||
| serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo | ||
| ) != key_public_key.public_bytes( | ||
| serialization.Encoding.DER, serialization.PublicFormat.SubjectPublicKeyInfo | ||
| ) | ||
|
|
||
|
|
||
| def _join_cert_chain(cert_match): | ||
|
|
@@ -933,8 +1029,6 @@ def client_cert_callback(): | |
| if isinstance(passphrase, str): | ||
| passphrase = passphrase.encode("utf-8") | ||
|
|
||
| from cryptography.hazmat.primitives import serialization | ||
|
|
||
| # First convert encrypted_key_bytes to PKey object | ||
| pkey = serialization.load_pem_private_key(key, password=passphrase) | ||
|
|
||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Moving
cryptographyto a top-level import breaksgcloudwhen it runs on a system Python withoutcryptographyinstalled.gcloudimports_mtls_helperon every API command and keepscryptographyoptional, so those commands will crash on startup withModuleNotFoundError. Can we keep thecryptographyimports inside the helper functions instead?