Automate Export certificates and keys from Kubernetes and import in Palo Alto Networks

In my precious post I explained how to export certificates and keys from Kubernetes and how to set a password on the key file for import in Palo Alto Networks (by hand). Since I’ve several services running on Kubernetes, all with there own certificate and key. I wanted to automate this process. This is good practice, especially since the certificates are relatively short lived, which means I need to renew the certificates on the firewall at least every 90 days. The first step I did was creating a bash script that would take care of this.

I know I’ve hardcoded the passphrase on the certificate key, for this temporarily solution this is fine. I can delete all crt and key files after the import.

Next step is of course to see if I can automate this when a certificate is renewed. The watch command could help with this.

#!/bin/bash
#
# Description: Get all certificates from all namespaces and import them into the Palo Alto Networks firewall
# Uses: awk, kubectl, openssl

FW_HOST="1.2.3.4"
API_KEY="VERYSECRETAPIKEY"

while read ns cert
do 
    echo "retrieving: $ns $cert"
    # Get the certificate and key from the secret
    kubectl get secrets -n $ns $cert -o json | jq -r '.data."tls.crt"' | base64 -d > $cert.crt
    kubectl get secrets -n $ns $cert -o json | jq -r '.data."tls.key"' | base64 -d > $cert.key
    # Set the password for the key - This is required for the import on the Palo Alto Networks firewall
    openssl rsa -aes256 -in $cert.key -out $cert.key -passout "pass:P@ssw0rd!" 
    # Import the certificate and key into the Palo Alto Networks firewall
    curl -k -X POST -F "file=@$cert.crt" "https://$FW_HOST/api/?key=$API_KEY&type=import&category=certificate&certificate-name=$cert&format=pem"
    curl -k -X POST -F "file=@$cert.key" "https://$FW_HOST/api/?key=$API_KEY&type=import&category=private-key&certificate-name=$cert&format=pem&passphrase=P@ssw0rd!"
done < <(kubectl get certificates -A -o custom-columns=NAMESPACE:.metadata.namespace,SECRET:.spec.secretName --no-headers --sort-by=.metadata.namespace | awk '{print $1 " " $2}')
Rob Maas
Rob Maas
Technical Challanger at ON2IT

If it is broken, fix it! If it ain’t broken, make it better!

Related