Skip to content

Instantly share code, notes, and snippets.

@amcginlay
Last active March 14, 2023 11:54
Show Gist options
  • Save amcginlay/8ffcbce115977b51b542ef5fd0c2d2b4 to your computer and use it in GitHub Desktop.
Save amcginlay/8ffcbce115977b51b542ef5fd0c2d2b4 to your computer and use it in GitHub Desktop.
How to enable PKI in K8s Vault for specified subdomains

Enable Secrets Engine PKI in K8s Vault (dev-mode)

Install Vault

helm repo add hashicorp https://helm.releases.hashicorp.com
helm -n vault install vault hashicorp/vault --create-namespace --set "server.dev.enabled=true"

Start session on Vault pod

kubectl -n vault exec -it vault-0 -- sh

Enable Secrets Engine PKI for subdomains of a given domain

domain=example.com
dotless_domain=$(echo ${domain} | sed 's/\./-dot-/g')

wget -O /home/vault/jq https://github.com/stedolan/jq/releases/download/jq-1.6/jq-linux64
chmod +x /home/vault/jq

vault secrets enable pki

vault write -field=certificate pki/root/generate/internal \
  common_name="${domain}" \
  ttl=87600h > /home/vault/CA_cert.crt

# Generate an intermediate CSR
vault write -format=json pki/intermediate/generate/internal \
  common_name="${domain} Intermediate Authority" | \
  /home/vault/jq -r '.data.csr' > /home/vault/pki_intermediate.csr

# Sign the intermediate CSR with the root certificate and save the generated certificate
vault write -format=json pki/root/sign-intermediate \
  csr=@/home/vault/pki_intermediate.csr \
  format=pem_bundle \
  ttl="43800h" | \
  /home/vault/jq -r '.data.certificate' > /home/vault/intermediate.cert.pem

# Import a signed certificate into Vault (technically optional)
# vault write pki/intermediate/set-signed \
#   certificate=@/home/vault/intermediate.cert.pem

# Create a role which allows subdomains.
vault write pki/roles/${dotless_domain} \
  allowed_domains="${domain}" \
  allow_subdomains=true max_ttl="720h"

# Request a test certificate in a subdomain based on the new role
vault write pki/issue/${dotless_domain} \
  common_name="test.${domain}" \
  ttl="24h"

# configure the CA URL (IS THIS REQUIRED?)
# vault write pki/config/urls \
#   issuing_certificates="http://vault.vault.svc.cluster.local:8200/v1/pki/ca"

exit

Port-forward from local machine (needs vault CLI, jq and openssl installed)

kubectl -n vault port-forward vault-0 8200:8200

# --- FOR UI ---
# navigate browser to http://localhost:8200 (in dev mode password is "root")

# --- FOR CLI ---
export VAULT_ADDR=http://localhost:8200 VAULT_TOKEN=root

vault list pki/certs

serial=<PICK_A_SERIAL_NUMBER>
vault read -format=json pki/cert/${serial} | \
  jq -r '.data.certificate' | \
  openssl x509 -noout -text

Remove Vault

helm -n vault uninstall vault
kubectl delete namespace vault
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment