Giter VIP home page Giter VIP logo

vault-kubernetes-workshop's Introduction

Vault Kubernetes Workshop on Google Cloud Platform

Prerequisites & Caveats

  • This workshop is designed to be run on Google Cloud Shell. It may work in other environments without modification, but the materials are only tested and guaranteed against Cloud Shell.

  • You must have a Google Cloud Platform account and be authenticated as a project owner. Again, if you are using Cloud Shell, this happens automatically. If you are running locally, you will need to download and install the Google Cloud SDK, and then authenticate to Google Cloud appropriately.

  • There are places where this workshop sacrifices "best practices" for "things feasible to complete in the duration of a workshop". In particular, this workshop generates self-signed SSL certificates and does not encrypt the resulting keys. For more details on a production-hardened setup, please see the Vault production hardening docs.

  • You must clone this repo:

    git clone https://github.com/sethvargo/vault-kubernetes-workshop
    cd vault-kubernetes-workshop
    

00 Install Vault

The first step is to install Vault. To install the Vault binary in the current working directory, run the install script.

./scripts/00-install-vault.sh

This will install Vault using the sethvargo/hashicorp-installer Docker container which verifies GPG signatures and checksums from the download.

This represents a "best practices" installation for installing secure software like Vault. By verifying the signature of the SHASUMs and then verifying the SHASUMs themselves, we guarantee both the integrity of the download and ensure the binary has not been tampered with beyond it's original publishing. For added security, you can download and compile Vault yourself from source, but that is out of scope for this workshop.

Cloud Shell does not persist things in /usr/local/bin or /usr/bin between sessions. As such, Vault will be installed in ~/bin. We recommend installing other binaries or software you need between sessions in this folder.

01 Enable Services

By default, a new Google Cloud project does not have many services enabled. Enable the required services (this only needs to be done once per project):

./scripts/01-enable-services.sh

This will make the necessary calls to enable the enable the right APIs on your project. This process can take some time, but it is idempotent (you can run it multiple times to achieve the same result).

02 Setup Storage

Vault requires a storage backend to persist its data. This workshop leverages Google Cloud Storage. Vault does not automatically create the storage bucket, so we need to create:

./scripts/02-setup-storage.sh

Cloud Storage bucket names must be globally unique across all of Google Cloud. The bucket will be named "${PROJECT}-vault-storage".

For security purposes, it is not recommended that other applications or services have access to this bucket. Even though the data is encrypted at rest, it is best to limit the scope of access as much as possible.

03 Setup KMS

Vault will leverage Google Cloud KMS to encrypt its unseal keys for auto-unsealing and auto-scaling purposes. We must create the KMS key in advance:

./scripts/03-setup-kms.sh

04 Create IAM Service Account

It is a best practice to create a limited, dedicated service account that has only the required permissions. Create a dedicated service account in the project and grant it the most minimal set of permissions, in particular:

  • The ability to read/write to the Cloud Storage bucket created above
  • The ability to encrypt/decrypt data with the KMS key created above
  • The ability to generate new service accounts (not required to use Vault, but helpful if you plan to use the Vault GCP secrets engine)
./scripts/04-create-iam-service-account.sh

05 Create Kubernetes Cluster

Next we need to create the Google Kubernetes Engine (GKE) cluster which will run Vault. It is recommended that you run Vault in a dedicated namespace or (even better) a dedicated cluster and a dedicated project. Vault will then act as a service with an IP/DNS entry that other projects and services query.

./scripts/05-create-k8s-cluster.sh

This will create the cluster and attach the service account created in the previous step to the cluster. It also ensures the cluster has the correct oauth scopes.

06 Create Public IP

This step creates and reserves a regional public IP address. In a future step, we will attach this reserved IP address to a Kubernetes load balancer. For now, we will just reserve the dedicated IP address.

./scripts/06-create-public-ip.sh

We use a regional IP address instead of a global IP address because global IPs perform load balancing at L7 whereas regional IP addresses perform load balancing at L4. Ideally we do not want the load balancer to perform TLS termination, and let Vault manage TLS, etc. While recent versions of Vault do support advanced routing like X-Forwarded-For headers, it is still a better practice to let Vault fully manage the TLS and thus use an L4 load balancer.

This step is not required if you are comfortable assigning your Vault Kubernetes service an ephemeral IP or will manage it via an external DNS service.

07 Create Certificates

This is arguably the most complex and nuanced piece of the workshop - generating Vault's certificate authority and server certificates for TLS. Vault can run without TLS, but this is highly discouraged. This step could be replaced with a trusted CA like Let's Encrypt, but that is out of scope for this workshop.

./scripts/07-create-certs.sh

This will create the Certificate Authority (ca.key, ca.crt) and Vault certificate (vault.key, vault.crt). In a future step, we will put these values in a Kubernetes secret so our pods can access them.

08 Create Config

Next we create the config map and secrets to store our data for our pods. The insecure data such as the storage bucket name and IP address are placed in a configmap. The secure data like the TLS certificates are put in a Kubernetes secret.

./scripts/08-setup-config.sh

09 Deploy Vault

The next step is to actually deploy Vault as a StatefulSet on Kubernetes. The reason we use a StatefulSet is two-fold:

  1. It guarantees exactly one service starts at a time. This is required by the vault-init sidecar service.

  2. It gives us consistent naming for referencing the Vault servers (which is nice for a workshop).

./scripts/09-deploy-vault.sh

Vault will automatically be initialized and unsealed via the vault-init service.

10 Deploy Load Balancer

Even though Vault is deployed, it is not publicly accessible. We need to create a Kubernetes Service Load Balancer to forward from the IP address reserved in the previous steps to the pods we just created.

./scripts/10-deploy-lb.sh

The load balancer listens on port 443 and forwards to port 8200 on the containers.

For production-hardened scenarios, you may want to include firewall rules to limit access to Vault at the network layer.

11 Setup Comms

Lastly, we need to configure our local Vault CLI to communicate with these newly-created Vault servers through the Load Balancer. Since we used custom TLS certificates, we'll need to trust the appropriate CA, etc. This will:

  • Set VAULT_ADDR to the Load Balancer address

  • Set VAULT_CAPATH to the path of the CA cert created in previous steps for properly verifying the TLS connection

  • Set VAULT_TOKEN to the decrypted root token by decrypting it from KMS

./scripts/11-setup-comms.sh

At this point, the local Vault CLI is configured to communicate with our Vault cluster. Verify by running vault status:

vault status

12 Setup Static KV

Next we will explore techniques for retrieving static (i.e. non-expiring) credentials from Vault. The kv secrets engine is commonly used with legacy applications which cannot handle graceful restarts or when secrets cannot be dynamically generated by Vault.

./scripts/12-setup-static-kv.sh

This will:

  1. Enable the KV secrets engine
  2. Create a policy to read data from a subpath
  3. Store some static username/password data in the secrets engine

Try reading back the secret by running:

vault kv get kv/myapp/config

You can also read the data via a request tool like curl.

curl -k -H "x-vault-token:${VAULT_TOKEN}" "${VAULT_ADDR}/v1/kv/myapp/config"

13 Another Cluster

Next we are going to create another Kubernetes cluster. There is no requirement that our Vault servers run under Kubernetes (they could be running on dedicated VMs or as a managed service). It is a best practice to treat the Vault server cluster as a "service" through which other applications and services request credentials. As such, moving forward, the Vault cluster will be treated simply as an IP address. We will not leverage K8S for "discovering" the Vault cluster, etc.

To put it another way, completely forget that Vault is running in Kubernetes. If it helps, think that Vault is running in a PaaS like Heroku instead.

Next create the Kubernetes cluster where our services will actually run. This is completely separate from the Vault K8S cluster. In fact, on GCP, is it recommended that you run these in completely separate projects. For the purpose of this workshop, we will run them in the same project.

./scripts/13-create-another-cluster.sh

This will provision a new Kubernetes cluster named "my-apps". We will deploy all future apps and services in this cluster.

Unlike the previous cluster, this cluster does not attach a service account.

14 Service Account

In our cluster, services will authenticate to Vault using the Kubernetes auth method. In this model, services present their JWT token to Vault as part of an authentication request. Vault takes that signed JWT token and, using the token reviewer API, verifies the token is authenticated. If the authentication is successful, Vault generates a token and maps a series of configured policies onto the token which is returned to the caller.

./scripts/14-create-service-account.sh

This will create a dedicated service account named "vault-auth" and grant that service account the ability to communicate with the token reviewer API.

15 Configure Vault to talk to Kubernetes

Next we need to configure the Vault cluster to talk to our new Kubernetes cluster ("my-apps"). We will need to give Vault the IP address of the cluster, the CA information, and the service account to use for accessing the token reviewer API.

./scripts/15-setup-vault-comms-k8s.sh

This process will:

  1. Look up the service account JWT token (this is how Vault will talk to the Kubernetes API)

  2. Extract the Kubernetes host from the local kube configuration (this where Vault will make API requests)

  3. Extract the Kubernetes CA from the local kube configuration (this is how Vault will authenticate requests)

  4. Enable the Kubernetes auth method in Vault

  5. Give Vault the service account JWT, host, and CA so that Vault can communicate with Kubernetes

There are other techniques for retrieving some of these values, but leveraging kubectl makes it easy to script.

16 Create KV Role

Typically this process is done by a security team or operations team. We need to configure Vault to map an application or service in Kubernetes to a series of policies in Vault. That way, when an application successfully authenticates to Vault via its JWT token, Vault knows which policies to assign to the response.

./scripts/16-create-kv-role.sh

This will create a role named "myapp-role" that permits pods in the "default" namespace with the "default" service account to receive a Vault token that has the "myapp-kv-rw" policy attached.

17 Sidecar Static App

This is one of the most common techniques for injecting Vault secrets into an application.

  1. An init container pulls the service account JWT token and performs the auth mechanism for that service account. If successful, it stores the resulting Vault token in somewhere on a shared volume mount.

  2. A tool like Consul Template runs as the first container. This tool uses the Vault token acquired by the init container and makes the appropriate API calls to Vault based off of a template file. The template file can reference one or more Vault credentials. Consul Template writes the rendered file with the secrets from Vault to a shared volume mount which the app reads.

  3. The app reads credentials. In this example, our application is a dummy application that just reads the contents of /etc/secrets/config repeatedly.

./scripts/17-run-kv-sidecar.sh

Verify the app is authenticating and retrieving secrets from Vault:

./scripts/kubectl-logs.sh kv-sidecar

18 Setup Dynamic Credentials

Next we configure Vault to generate dynamic credentials. Vault can generate many types of dynamic credentials like database credentials, certificates, etc. For this example, we will leverage the GCP secrets engine to dynamically generate Google Cloud Platform CloudSQL MySQL users.

./scripts/18-setup-dynamic-creds.sh

This will:

  1. Create a CloudSQL database

  2. Enable the database secrets engine

  3. Configure the database secrets engine

  4. Create a "role" which configures the permissions the SQL user has

  5. Create a new policy which allows generating these dynamic credentials

  6. Update the Vault Kubernetes auth mapping to include this new policy when authenticating

This process can take up to 10 minutes to complete.

19 Sidecar Dynamic App

In this example, we follow the same pattern as the static KV secrets, but our sidecar application will pull dynamic credentials from Vault. In this case, we will be creating a database password.

./scripts/19-run-db-sidecar.sh

This also configures a command to run which will signal the application when the underlying service account changes. This is important as we need to notify the application (which is not aware of Vault's existence) that it should reload its configuration.

Verify the app is authenticating and retrieving secrets from Vault:

./scripts/kubectl-logs.sh db-sidecar

vault-kubernetes-workshop's People

Contributors

daftkid avatar dcaba avatar narendrakadali avatar sethvargo avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vault-kubernetes-workshop's Issues

--scope collides with --service-account in step 7

Step 7

gcloud container clusters create vault \
>   --cluster-version 1.13 \
>   --enable-autorepair \
>   --enable-autoupgrade \
>   --enable-ip-alias \
>   --machine-type n1-standard-1 \
>   --node-version 1.13 \
>   --num-nodes 1 \
>   --region us-east1 \
>   --scopes cloud-platform \
>   --service-account "${SERVICE_ACCOUNT}"
ERROR: (gcloud.container.clusters.create) argument --service-account: At most one of --service-account | --no-enable-cloud-endpoints --scopes may be specified.

Cannot create configmaps based on tutorial commands

ed@cloudshell:~ (xxxxxxxxxx)$ kubectl create configmap vault \
>   --from-literal "load_balancer_address=$(vault-lb-ip)" \
>   --from-literal "gcs_bucket_name=${GOOGLE_CLOUD_PROJECT}-vault-storage" \
>   --from-literal "kms_project=${GOOGLE_CLOUD_PROJECT}" \
>   --from-literal "kms_region=us-east1" \
>   --from-literal "kms_key_ring=vault" \
>   --from-literal "kms_crypto_key=vault-init" \
>   --from-literal="kms_key_id=projects/$(google-project)/locations/$(google-region)/keyRings/vault/cryptoKeys/vault-init"
-bash: vault-lb-ip: command not found
-bash: google-project: command not found
-bash: google-region: command not found
configmap/vault created

This is in the google cloud shell using bash. It does not reference those values anywhere before this page and those values don't work on google cloud shell.

consul-template doesn't renew the vault token

Hi, Thanks for the amazing workshop!

I'm new in Vault & consul-template. I notice that you set the vault_agent_token_file (https://github.com/sethvargo/vault-kubernetes-workshop/blob/master/k8s/kv-sidecar.yaml#L79) and i saw the official consul-template repo says that if we specify vault_agent_token_file , the consul-template will not try to renew the Vault token (https://github.com/hashicorp/consul-template#configuration-file-format) and it does happen to me. The consul-template doesn't seems to renew the vault token after the lease expired. Is there something I miss?

Here's consul-template log:

2019/06/11 02:58:03.816250 [WARN] vault.read(gcp/test/demo/key/demo-project-viewer): renewer returned (maybe the lease expired)
2019/06/11 02:58:13.219535 [WARN] (view) vault.read(secret/test/data-secret): vault.read(secret/test/data-secret): Error making API request.

URL: GET https://10.x.x.x/v1/secret/test/data-secret
Code: 403. Errors:

* permission denied (retry attempt 1 after "1s")

Here's my CT_LOCAL_CONFIG (basically the same as yours)

vault {
  vault_agent_token_file = "/var/run/secrets/vaultproject.io/.vault-token"

  ssl {
    ca_cert = "/etc/vault/tls/ca.pem"
  }

  retry {
    backoff = "1s"
  }
 }

template {
  contents = <<EOH
    {{- with secret "secret/test/data-secret" -}}
    {{- .Data.message -}}
    {{- end -}}
  EOH
  destination = "/etc/secrets/static.txt"
}
template {
  contents = <<EOH
    {{- with secret "gcp/test/demo/key/demo-project-viewer" -}}
    {{- .Data.private_key_data | base64Decode -}}{{- end -}}
  EOH
  destination = "/etc/secrets/dynamic.json"
}

Second container which pulls vault image goes in CrashLoopBackOff

@sethvargo

So there are 2 containers which runs inside one pod, however image of vault-init container gets pulled successfully and get the container running, however there seems to be a problem with the second (vault) image. I even changed the vault image from (1.0.2) in your master k8s/vault.yaml to 1.2.2.(in my local), however wasn't fruitful. Both of the images tags aren't working(1.0.2, and 1.2.2). Container keeps on restarting. No logs can be seen as such. Please help us out. Thanks in advance.

$ kubectl get pods

NAME        READY      STATUS   RESTARTS   AGE
vault-0        1/2            Error             5          3m58s
$ kubectl describe pod vault-0

Successfully pulled image "registry.hub.docker.com/library/vault:1.2.2"
Created container
Started container
Back-off restarting failed container

PS: We are running everything inside Google cloud shell, and have been following everything presented in this link:

https://codelabs.developers.google.com/codelabs/vault-on-gke/index.html?index=..%2F..cloud#0

Attached is the screenshot of error for better understanding:

Screenshot 2019-09-09 at 2 53 06 PM

Modified(new) vault.yaml:

Screenshot 2019-09-09 at 2 57 17 PM

Missing configmap values?

This is more of a doubt, but we declare configmap vault to have values

    --from-literal "load_balancer_address=${LB_IP}" \
    --from-literal "gcs_bucket_name=${GCS_BUCKET}" \
    --from-literal "kms_key_id=${KMS_KEY}"

but on vault deployment file we use many other values

env:
        - name: GCS_BUCKET_NAME
          valueFrom:
            configMapKeyRef:
              name: vault
              key: gcs_bucket_name
        - name: KMS_PROJECT
          valueFrom:
            configMapKeyRef:
              name: vault
              key: kms_project
        - name: KMS_REGION
          valueFrom:
            configMapKeyRef:
              name: vault
              key: kms_region
        - name: KMS_KEY_RING
          valueFrom:
            configMapKeyRef:
              name: vault
              key: kms_key_ring
        - name: KMS_CRYPTO_KEY
          valueFrom:
            configMapKeyRef:
              name: vault
              key: kms_crypto_key
        - name: LOAD_BALANCER_ADDR
          valueFrom:
            configMapKeyRef:
              name: vault
              key: load_balancer_address

Aren't we missing some values here? I'm asking this because my pods are failing to deploy because of this:

image

Minor typo

Hi,

"vault secrets enable vk" should be "vault secrets enable kv".

Thanks.

ERROR: (gcloud.kms.decrypt) INVALID_ARGUMENT: Decryption failed: verify that 'name' refers to the correct CryptoKey.

Hello,

I am following the exact steps from the tutorial,
https://codelabs.developers.google.com/codelabs/vault-on-gke/index.html?index=..%2F..cloud#12

however I keep getting this error

CommandException: No URLs matched: gs://ztar-hashicorp-vault-dev-vault-storage/root-token.enc
ERROR: (gcloud.kms.decrypt) INVALID_ARGUMENT: Decryption failed: verify that 'name' refers to the correct CryptoKey.

Looked inside the storage and there are two folders core and sys. What am I missing here?

Thank you

Reading vault token in sidecar container from disk

When using the official consul-template image hashicorp/consul-template:alpine, it will not load the vault token from /home/vault/.vault-token. Instead it expects the token to be present in the VAULT_TOKEN environment variable.

Is there any way in your setup to use it with the official conul-template image?

Vault root_token.env is missing

Hi, I have followed all the guides you have written for us.
First of all, thank you for your guides. I found it helpful for me.
After the deployment of vault in GKE, I could not find the root_token.env on my GCS.
The only way I could do to grep the token was first to initialize the vault with dev mode. The token would appear on the log.
Any idea why the root_token.env is missing by following the guides?

Is the consul side car really required?

@sethvargo Just curious to know, if I am a dev heavily using spring boot, I would not need the consul side car fetching the secrets for me right? I would rather have just the init container do the auth flow, fetch the vault token and give the token to spring boot via annotations and that will fetch the required secrets for me. Does it make sense to avoid the consul side car in this case?

the kv-sidecar pod remains in CrashLoopBackOff.

Hi @sethvargo @gdwikir

Thanks for the amazing workshop. I am almost done with setting up everything, and everything seemed to be working fine until I came across this error. Not so sure whether anyone else is facing this issue or not.

Here are the logs

$ kubectl logs -l app=kv-sidecar -c vault-authenticator

2019/09/25 07:36:48 failed to get successful response: &http.Response{Status:"500 Internal Server Error", StatusCode:500, Proto:"HTTP/2.0", ProtoMajor:2, ProtoMinor:0, Header:http.Header{"Cache-Control":[]string{"
no-store"}, "Content-Length":[]string{"52"}, "Content-Type":[]string{"application/json"}, "Date":[]string{"Wed, 25 Sep 2019 07:36:48 GMT"}}, Body:http2.transportResponseBody{cs:(*http2.clientStream)(0xc00009ea00)}
, ContentLength:52, TransferEncoding:[]string(nil), Close:false, Uncompressed:false, Trailer:http.Header(nil), Request:(*http.Request)(0xc0000d6000), TLS:(*tls.ConnectionState)(0xc000082580)}, {"errors":["could no
t load backend configuration"]}

Image is attached below:

Screenshot 2019-09-25 at 1 09 36 PM

I even tried changing the vault-authenticator image version to latest, still the error seems to persist.

Screenshot 2019-09-25 at 1 15 43 PM

And because of this failed container, consul-template remains in initialising stage(as it is waiting for vault-authenticator to come up.)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.