\ /
Ansible  Automation  Security  Case study  Infrastructure 

Automated TLS Certificate Management

Automated TLS Certificate Management

[Versione italiana di seguito]

In today’s modern digital age communication security is a fundamental requirement for companies and users. Transport Layer Security (TLS) certificates play a key role in this context ensuring that information exchanged between client and server is encrypted and secure.

The Importance of TLS Certificates

TLS certificates are an essential to establishing secure connections. They:

  • Ensure Encryption: They protect data in transit from eavesdropping and tampering.
  • They Authenticate Servers: They confirm the identity of the server with which the client is communicating, reducing the risk of man-in-the-middle attacks.
  • They Authenticate Clients: In the case of using an Mtls connection in addition to server authentication, they confirm the client’s identity.
  • They increase User Trust: The lock icon in the address browser bar indicating an HTTPS connection that reassures users about the website security.

TLS Certificate Management Challenge

TLS Manual management certificates can be complex and error-prone, leading to expired certificates or misconfigurations that jeopardize the security and availability of services. To address these issues, many organizations are adopting automated certificate management.

Automated Management TLS Certificates Implementation

A popular method of implementing autonomous certificate management is through the use of the Automatic Certificate Management Environment (ACME) protocol for example by taking advantage of the CA Let's Encrypt. However, this method is not always the most suitable and for several projects may not be the optimal choice. Below we present a highly flexible and customizable solution that allows the implementation of automated certificate management in any context.

Components:

  • Certification Authority (CA) with API service: RESTful service that enables certificate management; below we will use Entrust's
  • Secrets Manager: below we will use HashiCorp Vault
  • Git repository: below we will use GitLab
  • Ansible: open source software to automate configuration, deployment, orchestration and many other IT processes
  • Red Hat Ansible Automation Platform (Optional): unified solution for strategic automation. Combines the security, functionality, integrations and flexibility needed to scale automation across domains, orchestrate essential workflows and optimize IT operations

The implementation involves the creation of at least two playbooks, one dedicated to the issuance of certificates and the other to the verification of expiration and subsequent renewal. The first playbook can be started manually or started via a webhook. In the latter case, Ansible Automation Platform can be configured in order to ensure the execution of the latest version of the playbook stored in the Git repository.

To ensure the proper certificate lifecycle management, each issued certificate will be automatically saved in a vault and its CN will be recorded in a YML file. This file will then be updated and archived in the git repository when the certificate issuance operation is complete with the goal of having a complete list of issued certificates and their usage.

Thanks to the community.crypto.ecs_certificate module, which is used by both playbooks, it is possible to interact with the Entrust API reducing deployment time. At this stage, ecs_certificate is used to proceed with the signing of the CSR (previously generated along with the relevant key via the community.crypto.openssl_privatekey and community.crypto.openssl_csr modules).

The ecs_certificate module will provide as output the signed certificate which (along with the key) will be saved on the Secret Manager.

Emissione Certificato.drawio.png

Example implementations point 3, signing the CSR:

- name: Create the private key
  community.crypto.openssl_privatekey:
    path: '{{ work_path_key }}'
    type: RSA
    size: 2048

- name: Generate CSR
  community.crypto.openssl_csr:
    path: '{{ work_path_csr }}'
    privatekey_path: '{{ new_cert_privatekey_path }}'
    common_name: '{{ common_name_certificate }}'
    digest: sha256

- name: Sign CSR with Entrust
  community.crypto.ecs_certificate:
    path: "{{path_certificate}}"
    full_chain_path: "{{path_chain}}"
    csr: '{{ work_path_csr }}'
    cert_type: STANDARD_SSL
    requester_name: "{{ name }}"
    requester_email: "{{ email }}"
    requester_phone: "{{ phone }}"
    entrust_api_user: "{{ api_user }}"
    entrust_api_key: "{{ api_key }}"
    entrust_api_client_cert_path: '{{ crt_client }}'
    entrust_api_client_cert_key_path: '{{ key_client }}'
    entrust_api_specification_path: https://cloud.entrust.net/EntrustCloud/documentation/cms-api-2.1.0.yaml
    remaining_days: "{{ remaining_days }}"
    request_type: new
    cert_expiry: "{{ lookup('pipe','date -d \"+12 month\" +%Y-%m-%d') }}"
  register: certificateResponse

The second playbook will be scheduled via cron or Ansible Automation Platform. Using the yml file created and managed by the first playbook, it will be able to download the certificate from the vault and check its expiration. In case the remaining days of validity of a certificate are less than a defined threshold, it will be able to launch the community.crypto.ecs_certificate module to renew it.

Rinnovo Certificato.png

Because of the flexibility of Ansible scripts it is possible to extend the actions taken to automatically install new certificates or to implement the process of issuing and renewing certificates for internal CAs or CAs that expose APIs for which there is no Ansible module.

Automated Management Advantages

Adopting TLS certificate management automated system offers several benefits:

  • Reduced Risk of Human Error: By automating processes you minimize the chances of misconfigurations or expired certificates.
  • Improved Security: Always up-to-date certificates ensure maximum security.
  • Operational Efficiency: Reduces the administrative burden on IT staff allowing them to focus on other critical tasks.

A use case: issuing client certificates (mTLS) for Confluent consumers (Kafka)

The customer wanted to automate the lifecycle certificates management used to authenticate Kafka consumers (in the Confluent deployment). The consumers are part of some micro-services deployed on an OpenShift cluster. The micro-services in order to connect to the Confluent cluster used manually created and renewed certificates. The implemented automation solution, resorting to the use of the two playbooks described earlier allows certificates automatic management used by Kafka clients. Using the GitOps methodology the request for new certificates is notified to Ansible via webhook which initiates the workflow described in the implementation section. With this declarative structure, the developer and infrastructure team have a tool for new certificate requests. A curiosity: During the development of the certificate renewal playbook, we observed that the ecs_certificate module was not in line with the API specification provided by Entrust. We therefore performed an analysis that led us to implement a fix for Ansible's crypto module, which was validated and merged into release 2.19.1 (https://github.com/ansible-collections/community.crypto/pull/740).

Conclusion

Automated TLS certificate management is not just a best practice but a necessity in a world where communication security is vital. In an ever-changing digital landscape automation becomes the pillar on which to build a solid cybersecurity strategy.


Versione italiana


Gestione Automatizzata dei certificati TLS

Nell'era digitale moderna, la sicurezza delle comunicazioni è requisito fondamentale per aziende e utenti. I certificati TLS (Transport Layer Security) svolgono un ruolo fondamentale in questo contesto, garantendo che le informazioni scambiate tra client e server siano criptate e sicure.

L'Importanza dei Certificati TLS

I certificati TLS sono essenziali per stabilire connessioni sicure. Essi:

  • Garantiscono la Crittografia: Proteggono i dati in transito da intercettazioni e manomissioni.
  • Autenticano i Server: Confermano l'identità del server con cui il client sta comunicando, riducendo il rischio di attacchi di tipo man-in-the-middle.
  • Autenticano i Client: Nel caso in cui si utilizzi una connessione mTLS, oltre all’autenticazione del server, confermano l'identità del client.
  • Aumentano la Fiducia degli Utenti: L'icona del lucchetto nella barra degli indirizzi di un browser, indicante una connessione HTTPS, rassicura gli utenti sulla sicurezza del sito web.

La Sfida della Gestione dei Certificati TLS

La gestione manuale dei certificati TLS può essere complessa e soggetta ad errori, portando a certificati scaduti o configurazioni errate che mettono a rischio la sicurezza e la disponibilità dei servizi. Per risolvere queste problematiche, molte organizzazioni stanno adottando la gestione automatizzata dei certificati.

Implementazione della Gestione Automatizzata dei Certificati TLS

Un metodo molto diffuso per implementare la gestione autonoma dei certificati è mediante l’utilizzo del protocollo ACME (Automatic Certificate Management Environment), ad esempio usufruendo della CA Let’s Encrypt.

Tuttavia, questo metodo non è sempre il più idoneo e per diversi progetti potrebbe non essere la scelta ottimale. Di seguito presentiamo una soluzione altamente flessibile e personalizzabile che permette di implementare la gestione automatizzata dei certificati in qualsiasi contesto. Componenti:

  • Certification Authority (CA) con servizio API: servizio RESTful che permette la gestione dei certificati; di seguito utilizzeremo quello di Entrust
  • Secrets Manager: di seguito utilizzeremo HashiCorp Vault
  • Repository git: di seguito utilizzeremo GitLab
  • Ansible: software open source che consente di automatizzare le procedure di configurazione, deploy, orchestrazione e molti altri processi IT
  • Red Hat Ansible Automation Platform (Opzionale): soluzione unificata per l'automazione strategica. Combina la sicurezza, le funzionalità, le integrazioni e la flessibilità necessarie per scalare l'automazione tra domini, orchestrare flussi di lavoro essenziali e ottimizzare le operazioni IT

L’implementazione prevede la creazione di almeno due playbook, uno dedicato all’emissione dei certificati e l'altro alla verifica della scadenza e conseguente rinnovo. Il primo playbook può essere avviato manualmente oppure avviato tramite un webhook. In quest’ultimo caso, è possibile configurare Ansible Automation Platform al fine di assicurare l’esecuzione dell’ultima versione del playbook archiviata nel repository Git. Per garantire la corretta gestione del ciclo di vita dei certificati, ogni certificato emesso verrà salvato automaticamente in un vault e il suo CN verrà registrato in un file YML. Questo file verrà quindi aggiornato ed archiviato nel repository git al termine dell’operazione di emissione del certificato, con lo scopo di avere un elenco completo dei certificati emessi e il loro utilizzo. Grazie al modulo community.crypto.ecs_certificate, utilizzato da entrambi i playbook, è possibile interagire con le API di Entrust riducendo i tempi di implementazione. In questa fase, ecs_certificate viene utilizzato per procedere con la firma della CSR (generata precedentemente insieme alla relativa chiave mediante i moduli community.crypto.openssl_privatekey e community.crypto.openssl_csr). Il modulo ecs_certificate fornirà come output il certificato firmato, il quale (insieme alla chiave) verrà salvato sul Secret Manager.

Emissione Certificato.png

Esempio implementazione punto 3, firma della CSR:

- name: Crea la chiave privata
  community.crypto.openssl_privatekey:
    path: '{{ work_path_chiave }}'
    type: RSA
    size: 2048

- name: Crea la CSR
  community.crypto.openssl_csr:
    path: '{{ work_path_csr }}'
    privatekey_path: '{{ new_cert_privatekey_path }}'
    common_name: '{{ common_name_certificato }}'
    digest: sha256

- name: Firma la CSR con Entrust
  community.crypto.ecs_certificate:
    path: "{{path_certificato}}"
    full_chain_path: "{{path_catena}}"
    csr: '{{ work_path_csr }}'
    cert_type: STANDARD_SSL
    requester_name: "{{ nome }}"
    requester_email: "{{ email }}"
    requester_phone: "{{ telefono }}"
    entrust_api_user: "{{ api_user }}"
    entrust_api_key: "{{ api_key }}"
    entrust_api_client_cert_path: '{{crt_client}}'
    entrust_api_client_cert_key_path: '{{chiave_client}}'
    entrust_api_specification_path: https://cloud.entrust.net/EntrustCloud/documentation/cms-api-2.1.0.yaml
    remaining_days: "{{ giorni_rimanenti }}"
    request_type: new
    cert_expiry: "{{ lookup('pipe','date -d \"+12 month\" +%Y-%m-%d') }}"
  register: rispostaCertificato

Il secondo playbook verrà schedulato tramite cron o Ansible Automation Platform. Utilizzando il file yml creato e gestito dal primo playbook, sarà in grado di scaricare il certificato dal vault e verificarne la scadenza. Nel caso in cui i giorni rimanenti di validità di un certificato siano inferiori a una soglia definita, sarà possibile avviare il modulo community.crypto.ecs_certificate per rinnovarlo.

Rinnovo Certificato_it.png

Grazie alla flessibilità degli script Ansible, è possibile estendere le azioni intraprese per installare automaticamente i nuovi certificati oppure implementare la procedura di emissione e rinnovo dei certificati per CA interne o CA che espongono delle API per cui non esiste un modulo Ansible.

Vantaggi della Gestione Automatizzata

Adottare un sistema automatizzato per la gestione dei certificati TLS offre numerosi vantaggi:

  • Riduzione del Rischio di Errori Umani: Automatizzando i processi, si minimizzano le possibilità di configurazioni errate o certificati scaduti.
  • Miglioramento della Sicurezza: Certificati sempre aggiornati garantiscono la massima sicurezza.
  • Efficienza Operativa: Riduce il carico amministrativo sul personale IT, permettendo loro di concentrarsi su altre attività critiche.  

Un caso d’uso: emissione dei certificati client (mTLS) per i consumer Confluent (Kafka)

Il cliente voleva automatizzare la gestione del ciclo di vita dei certificati utilizzati per l’autenticazione dei consumer Kafka (nella distribuzione Confluent). I consumer fanno parte di alcuni micro-servizi deployati su un cluster OpenShift. I micro-servizi, per potersi connettere al cluster Confluent, utilizzavano certificati creati e rinnovati manualmente.

La soluzione di automazione implementata, ricorre all’utilizzo dei due playbook descritti precedentemente, permette la gestione automatica dei certificati utilizzati dai client Kafka. Utilizzando la metodologia GitOps, la richiesta dei nuovi certificati viene notificata ad Ansible tramite webhook, il quale avvia il workflow descritto nel paragrafo dell’implementazione. Con questa struttura dichiarativa, il team degli sviluppatori e infrastruttura ha a disposizione un tool per le richieste di nuovi certificati.

Curiosità: Durante lo sviluppo del playbook di rinnovo certificati, abbiamo osservato che il modulo ecs_certificate non era in linea con le specifiche delle API fornite da Entrust. Abbiamo dunque effettuato una analisi che ci ha portato a realizzare una fix per il modulo crypto di Ansible, la quale è stata validata e mergiata nella release 2.19.1 (https://github.com/ansible-collections/community.crypto/pull/740).

Conclusione

La gestione automatizzata dei certificati TLS non è solo una best practice, ma una necessità in un mondo dove la sicurezza delle comunicazioni è vitale. In un panorama digitale in continua evoluzione, l'automazione diventa il pilastro su cui costruire una solida strategia di sicurezza informatica.

comments powered by Disqus