How to store/retrieve KMS encrypted .enc file in/from kubernetes secrets

11/6/2019

I have an .enc file that has been encrypted by a GCP KMS key. I stored this encrypted file as a secret in kubernetes . Kubernetes cluster has permissions to access KMS key. Now i want to decrypt stored encrypted file using key when container is running. My service is written in python. How can i decrypt stored encrypted file using a python script?

-- Nipu
google-cloud-kms
google-kubernetes-engine
kubernetes-secrets

1 Answer

11/6/2019

I think you may be confusing two concepts here. If you're using GKE Application-layer encryption, your cluster needs IAM permissions to talk to KMS. You, as the user, never directly encrypt secrets. When you run kubectl create secret, for example, GKE will automatically encrypt the secret before saving it to etcd. When you request the secret, GKE will automatically decrypt it.

If you want to encrypt the secret out-of-bands, your Kubernetes cluster should not have permission to use the KMS key. Neither Kubernetes nor etcd will ever see the plaintext secret. You encrypt it locally on your computer and save the encrypted data as a secret in Kubernetes. When you want to retrieve the plaintext, your pod/service will need to request the Kubernetes secret and then make the necessary API calls to Cloud KMS to decrypt the secret. Here's some sample Python code that could decrypt the secret:

def decrypt(client, s):
    if not s:
        raise ValueError('ciphertext is missing')

    response = client \
        .projects() \
        .locations() \
        .keyRings() \
        .cryptoKeys() \
        .decrypt(name=crypto_key_id, body={"ciphertext":s}) \
        .execute()

    return base64.b64decode(response['plaintext']).decode('utf-8').strip()
-- sethvargo
Source: StackOverflow