Commit 58d4a68e authored by Guillermo Sanz López's avatar Guillermo Sanz López
Browse files

fix common name signatur in vault and change spanish comments

parent 4658c29f
Loading
Loading
Loading
Loading
Loading
+10 −35
Original line number Diff line number Diff line
@@ -15,12 +15,9 @@ ATTEMPT=0
SUCCES_OPERATION=false


# ==============================================================
# TEMP FIX: Force CCF ID (bypass Helper)
# ==============================================================
# CCF_ID="CCF11111111-2222-3333-4444-555555555555"
# echo "[WARN] Using FORCED CCF_ID=${CCF_ID} (helper bypassed)"

###############################################################
# 1) FETCH CA ROOT CERTIFICATE FROM VAULT
###############################################################

echo "[STEP] Fetching CA root certificate from Vault"
while [ $ATTEMPT -lt $MAX_RETRIES ]; do
@@ -77,13 +74,13 @@ if [ ! -f server.crt ]; then
    echo "[STEP 3] Generating CSR for CAPIF service"
    echo "[INFO] Common Name (CN): $CAPIF_HOSTNAME"

    # genera un csr usando servery.key
    # Generate CSR using the previously generated server.key
    openssl req -new -key server.key \
        -subj "/CN=$CAPIF_HOSTNAME" \
        -addext "subjectAltName=DNS:$CAPIF_HOSTNAME" \
        -out server.csr

    # convierte el csr a una sola línea con \n para que se pueda enviar en el cuerpo del request a Vault (que espera un JSON)
    # Convert the CSR to a single line with \n so it can be sent in the body of the request to Vault (which expects JSON)
    CSR_CONTENT=$(sed ':a;N;$!ba;s/\n/\\n/g' server.csr)

    echo "[STEP 3] CSR generated successfully"
@@ -97,41 +94,19 @@ if [ ! -f server.crt ]; then
        ATTEMPT=$((ATTEMPT + 1))
        echo "[STEP 3] Attempt $ATTEMPT/$MAX_RETRIES – Signing CSR in Vault"


        echo "---------------- CURL REQUEST ----------------"
        echo "curl -X POST \\"
        echo "  -H \"X-Vault-Token: $VAULT_TOKEN\" \\"
        echo "  -d '{\"csr\":\"$CSR_CONTENT\",\"format\":\"pem_bundle\",\"common_name\":\"$CAPIF_HOSTNAME\"}' \\"
        echo "  \"$VAULT_ADDR/v1/pki_int/sign/my-ca\""
        echo "----------------------------------------------"

        # POST /v1/pki_int/sign/my-ca (endpoint del intermediate CA para firmar el CSR))
        # POST /v1/pki_int/sign/my-ca intermediate's endpoint to sign the CSR
        SIGN_RESPONSE=$(curl -s -X POST \
            -H "X-Vault-Token: $VAULT_TOKEN" \
            -d "{\"csr\":\"$CSR_CONTENT\",\"format\":\"pem_bundle\"}" \
            -d "{\"csr\":\"$CSR_CONTENT\",\"format\":\"pem_bundle\",\"common_name\":\"$CAPIF_HOSTNAME\"}" \
            "$VAULT_ADDR/v1/pki_int/sign/my-ca")

        # SIGN_RESPONSE, te devuelve un formato PEM bundle con el certificado firmado + la cadena de certificados intermedios (pero sin el root).
        # SIGN_RESPONSE; return a PEM bundle format with the signed certificate + intermediate certificate chain (but without the root).

        echo "---------------- VAULT RESPONSE ---------------"
        echo "$SIGN_RESPONSE"
        echo "----------------------------------------------"

        # el responde contiene un campo dato formado por:
        # ca_chain => bundle con intermediate + root.  Basicamnete lo mismo que bundle.crt pero separados por comillas en vez de concatenados en un solo archivo
        # certificate => el certificado firmado para el servidor. Incluye Certificado del servidor, Intermediate CA y Root CA (en ese orden) pero todo en un MISMO bloque PEM.
        # issuing_ca => el certificado del intermediate CA que ha firmado el CSR (sin el root CA, sin concatenar, solo el intermediate).

        # CERT=$(echo "$SIGN_RESPONSE" | jq -r '.data.certificate')
        #CERT=$(printf '%s' "$SIGN_RESPONSE" | jq -r '.data.certificate // empty')
        CERT=$(printf '%s' "$SIGN_RESPONSE" | jq -er '.data.certificate')



        if [ -n "$CERT" ] && [ "$CERT" != "null" ]; then
            echo "$CERT" > server.crt
            echo "Server certificate successfully signed and saved."
            # osea en server.crt tengo. Server.crt + intermediate CA + root CA (en ese orden) pero todo en un MISMO bloque PEM.
            SUCCESS_OPERATION=true
            break
        else
@@ -158,13 +133,13 @@ CCF_ID=""

echo "[STEP] Fetching CCF_ID from Helper: $HELPER_URL"

# Retry loop to get CCF_ID from Helper
while [ $ATTEMPT_CCFID -lt $MAX_RETRIES ]; do
  ATTEMPT_CCFID=$((ATTEMPT_CCFID + 1))
  echo "[INFO] Attempt $ATTEMPT_CCFID/$MAX_RETRIES – GET $HELPER_URL"

  RESP=$(curl -s --connect-timeout 5 --max-time 10 "$HELPER_URL" || true)

  # Si tienes jq en nginx:
  CCF_ID=$(printf '%s' "$RESP" | jq -r '.ccf_id // empty' 2>/dev/null || true)

  if [ -n "$CCF_ID" ]; then
@@ -184,7 +159,6 @@ fi




###############################################################
# 5) STORE CERTIFICATES IN VAULT UNDER capif/<ccf_id>
###############################################################
@@ -194,6 +168,7 @@ SERVER_CRT_ESCAPED=$(sed ':a;N;$!ba;s/\n/\\n/g' server.crt)
SERVER_KEY_ESCAPED=$(sed ':a;N;$!ba;s/\n/\\n/g' server.key)
CA_ESCAPED=$(sed ':a;N;$!ba;s/\n/\\n/g' ca.crt)

# Store the server certificate, private key and CA certificate in Vault under secret/data/capif/<ccf_id>/nginx
VAULT_RESPONSE=$(curl -s -w "%{http_code}" -o /tmp/vault_resp.json \
  -X POST \
  -H "X-Vault-Token: $VAULT_TOKEN" \
+15 −25
Original line number Diff line number Diff line
@@ -20,17 +20,16 @@ vault secrets enable pki
# Modify pki engine settings
vault secrets tune -max-lease-ttl=87600h pki

# Crea un root CA interno de VAULT, endpoint pki/root/generate/internal
# internal = Vault genera y guarda la clave privada del root internamente.
# Create a root CA with a common name of "capif" and an issuer name of "root-2026". The certificate will be valid for 87600 hours (10 years).
# pki/root/generate/internal => vault generates and store the root CA private key internally and returns the certificate.
vault write -field=certificate \
     pki/root/generate/internal \
     common_name="capif" \
     issuer_name="root-2026" \
     ttl=87600h > root_2026_ca.crt

# Configura URLs que VAULT meterá en los certificados emitidos
# issuing_certificates: dónde se publica el certificado de la CA.
# crl_distribution_points: dónde se publica la CRL (revocaciones).
# Configure the URLs that Vault will include in the issued certificates:
# issuing_certificates: where the CA certificate is published. crl_distribution_points: where the CRL (Certificate Revocation List) is published.
vault write pki/config/urls \
     issuing_certificates="$VAULT_ADDR/v1/pki/ca" \
     crl_distribution_points="$VAULT_ADDR/v1/pki/crl"
@@ -40,27 +39,19 @@ vault write pki/config/urls \
# 2) INTERMEDIATE CA
############################################################

# Habilita otro engine PKI, pero en ruta pki_int/.
# Enable another PKI engine, but at path pki_int.
vault secrets enable -path=pki_int pki

# Ajusta el TTL máximo del engine intermediate.
# Adjust the maximum TTL of the intermediate engine.
vault secrets tune -max-lease-ttl=43800h pki_int


# Generate a CSR for the intermediate CA. This will create a new private key for the intermediate CA and return a CSR that we will sign with the root CA. The CSR is saved in a file called pki_intermediate.csr.
vault write -format=json pki_int/intermediate/generate/internal \
     common_name="capif Intermediate Authority" \
     issuer_name="capif-intermediate" \
    | jq -r '.data.csr' > pki_intermediate.csr

# Explicación de este comando:
# vault write   --> haz una llamada al API de Vault para escribir/ejecutar algo (normalemente equivale a un POST)
#      -format=json  --> devuélveme la respuesta en JSON completo
#      pki_int/intermediate/generate/internal \  -->  Es la ruta del endpoint dentro de Vault (la “API path” del motor PKI).    intermediate/generate/internal= genera una CA intermedia con clave privada interna y devuélveme un CSR”.
#      common_name="capif Intermediate Authority" \
#      issuer_name="capif-intermediate" \
#     | jq -r '.data.csr' > pki_intermediate.csr -->  Toma la respuesta JSON, extrae el campo .data.csr (que es el CSR generado por Vault) y guárdalo en un archivo llamado pki_intermediate.csr.

# Sign the intermediate CA with the root CA --> obtiene capif_intermediate.cert.pem
# Sign the intermediate CA with the root CA --> capif_intermediate.cert.pem
vault write -format=json \
     pki/root/sign-intermediate \
     issuer_ref="root-2026" \
@@ -75,11 +66,11 @@ vault write pki_int/intermediate/set-signed certificate=@capif_intermediate.cert
# 3) CONFIGURE SIGNING ROLE
############################################################

# Crea un “role” llamado my-ca dentro de pki_int. Ese role define las reglas para emitir certificados.
# Creates a role named my-ca within pki_int. This role defines the rules for issuing certificates.
vault write pki_int/roles/my-ca \
     use_csr_common_name=true \
     require_cn=true \
     use_csr_sans=true \
     use_csr_common_name=false \
     require_cn=false \
     use_csr_sans=false \
     allow_any_name=true \
     allow_bare_domains=true \
     allow_glob_domains=true \
@@ -90,7 +81,7 @@ vault write pki_int/roles/my-ca \
# 4) CA BUNDLE
# ============================================================

# Guarda el certificado intermedio y el root en un mismo fichero (CA bundle) para que nginx pueda usarlo como cadena de confianza.
# Save the intermediate and root certificates in a single file (CA bundle) so that nginx can use it as a trust chain.
vault kv put secret/ca ca=@capif_intermediate.cert.pem

echo "[INFO] CA bundle stored at secret/ca"
@@ -98,15 +89,14 @@ echo "[INFO] CA bundle stored at secret/ca"

# ============================================================
# OPTIONAL: Create read-only token for CA access
# (Not required in local dev, required in prod)
# ============================================================

# vriables para crear una política y token de solo lectura para el CA
# variables for creating a read-only policy and token for the CA
POLICY_NAME="my-policy"
POLICY_FILE="my-policy.hcl"
TOKEN_ID="read-ca-token"

# Crea un fichero HCL con la política de solo lectura para el CA
# Create a HCL file with the read-only policy for the CA
echo "path \"secret/data/ca\" {
  capabilities = [\"read\"]
}" > "$POLICY_FILE"