Saltar al contenido

Descubriendo la Verdad Detrás de los Secretos de Kubernetes

man in white dress shirt wearing black framed eyeglasses

Foto por krakenimages en Unsplash

Hemos estado hablando recientemente sobre ConfigMap como uno de los objetos para almacenar una configuración diferente para cargas de trabajo basadas en Kubernetes. Pero, ¿qué pasa con los datos sensibles?

Esta es una pregunta interesante, y la respuesta inicial de la plataforma Kubernetes fue proporcionar un objeto Secrets. Basado en su definición del sitio web oficial de Kubernetes, definen los secretos de esta manera:

Un Secret es un objeto que contiene una pequeña cantidad de datos sensibles como una contraseña, un token o una clave. Tal información podría de otro modo ser puesta en una especificación de Pod o en una imagen de contenedor. Usar un Secret significa que no necesitas incluir datos confidenciales en el código de tu aplicación

Entonces, por defecto, los secretos son lo que deberías usar para almacenar tus datos sensibles. Desde la perspectiva técnica, para usarlos, se comportan de manera muy similar a ConfigMap, por lo que puedes vincularlo a las diferentes variables de entorno, montarlo dentro de un pod, o incluso tener usos específicos para gestionar credenciales para diferentes tipos de cuentas como Cuentas de Servicio. Esto clasifica los diferentes tipos de secretos que puedes crear:

  • Opaco: Esto define un secreto genérico que puedes usar para cualquier propósito (principalmente datos de configuración o archivos de configuración)
  • Token de Cuenta de Servicio: Esto define las credenciales para cuentas de servicio, pero esto está obsoleto y ya no se usa desde Kubernetes 1.22.
  • Credenciales de Registro Docker: Esto define credenciales para conectarse al registro Docker para descargar imágenes como parte de tu proceso de implementación.
  • Autenticación Básica o SSH: Esto define secretos específicos para manejar la autenticación.
  • Secreto TLS:
  • Secretos de Arranque:

Pero, ¿es seguro usar Kubernetes Secrets para almacenar datos sensibles? La respuesta principal para cualquier pregunta en cualquier tema relacionado con la tecnología es: Depende. Pero ha surgido cierta controversia que este tema también se cubre en la página oficial de Kubernetes, destacando los siguientes aspectos:

Los Secrets de Kubernetes se almacenan, por defecto, sin cifrar en el almacén de datos subyacente del servidor API (etcd). Cualquiera con acceso a la API puede recuperar o modificar un Secret, y también cualquiera con acceso a etcd. Además, cualquiera que esté autorizado para crear un Pod en un espacio de nombres puede usar ese acceso para leer cualquier Secret en ese espacio de nombres; esto incluye acceso indirecto como la capacidad de crear un Deployment.

Entonces, lo principal es que, por defecto, esta es una forma muy, muy insegura. Parece más una categorización de los datos que un manejo seguro adecuado. Además, Kubernetes proporciona algunos consejos para intentar hacer esta alternativa más segura:

  • Habilitar el Cifrado en Reposo para los Secrets.
  • Habilitar o configurar reglas RBAC que restrinjan la lectura de datos en los Secrets (incluyendo medios indirectos).
  • Cuando sea apropiado, también usar mecanismos como RBAC para limitar qué principales tienen permitido crear nuevos Secrets o reemplazar los existentes.

Pero eso puede no ser suficiente, y eso ha creado espacio para que terceros y proveedores de la nube ofrezcan su solución que cubra estas necesidades y al mismo tiempo también ofrezca características adicionales. Algunas de estas opciones son las que se muestran a continuación:

  • Sistemas de Gestión de Claves en la Nube: Prácticamente todos los grandes proveedores de la nube proporcionan alguna forma de Gestión de Secretos para ir más allá de estas características y mitigar esos riesgos. Si hablamos de AWS, está AWS Secrets Manager , si hablamos de Azure, tenemos Azure Key Vault , y en el caso de Google, también tenemos Google Secret Manager.
  • Sealed Secrets es un proyecto que intenta extender los Secrets para proporcionar más seguridad, especialmente en el enfoque de Configuración como Código, ofrece una forma segura de almacenar esos objetos en el mismo tipo de repositorios que expones cualquier otro archivo de recursos de Kubernetes. En sus propias palabras, “El SealedSecret solo puede ser descifrado por el controlador que se ejecuta en el clúster de destino, y nadie más (ni siquiera el autor original) puede obtener el Secret original del SealedSecret.”
  • Gestores de Secretos de terceros que son similares a los de los Proveedores de la Nube que permiten un enfoque más independiente, y hay varios jugadores aquí como Hashicorp Vault o CyberArk Secret Manager
  • Finalmente también, Spring Cloud Config puede proporcionar seguridad para almacenar datos que están relacionados con conceptos de configuración sensibles como contraseñas y al mismo tiempo cubre la misma necesidad que proporciona ConfigMap desde una perspectiva unificada.

Espero que este artículo haya ayudado a entender el propósito de los Secrets en Kubernetes y, al mismo tiempo, los riesgos respecto a su seguridad y cómo podemos mitigarlos o incluso confiar en otras soluciones que proporcionen una forma más segura de manejar esta pieza crítica de información.

Discovering The Truth Behind Kubernetes Secrets

man in white dress shirt wearing black framed eyeglasses

Photo by krakenimages on Unsplash

We have been talking recently about ConfigMap being one of the objects to store a different configuration for Kubernetes based-workloads. But what happens with sensitive data?

This is an interesting question, and the initial answer from the Kubernetes platform was to provide a Secrets object. Based on its definition from the Kubernetes official website, they define secrets like this:

A Secret is an object that contains a small amount of sensitive data such as a password, a token, or a key. Such information might otherwise be put in a Pod specification or in a container image. Using a Secret means that you don’t need to include confidential data in your application code

So, by default, secrets are what you should use to store your sensitive data. From the technical perspective, to use them, they behave very similar to ConfigMap, so you can link it to the different environment variables, mount it inside a pod, or even have specific usages for managing credentials for different kinds of accounts such as Service Accounts. This classifies the different types of secrets that you can create:

  • Opaque: This defines a generic secret that you can use for any purpose (mainly configuration data or configuration files)
  • Service-Account-Token: This defines the credentials for service accounts, but this is deprecated and no longer in use since Kubernetes 1.22.
  • Docker-Registry Credentials: This defines credentials to connect to the Docker registry to download images as part of your deployment process.
  • Basic or SSH Auth: This defines specific secrets to handle authentication.
  • TLS Secret:
  • Bootstrap Secrets:

But is it safe to use Kubernetes Secrets to store sensitive data? The main answer for any question in any tech-related topic is: It depends. But some controversy has arisen that this topic is also covered in the official Kubernetes page, highlighting the following aspects:

Kubernetes Secrets are, by default, stored unencrypted in the API server’s underlying data store (etcd). Anyone with API access can retrieve or modify a Secret, and so can anyone with access to etcd. Additionally, anyone who is authorized to create a Pod in a namespace can use that access to read any Secret in that namespace; this includes indirect access such as the ability to create a Deployment.

So, the main thing is, by default, this is a very, very insecure way. It seems more like a categorization of the data than a proper secure handle. Also, Kubernetes provide some tips to try to make this alternative more secure:

  • Enable Encryption at Rest for Secrets.
  • Enable or configure RBAC rules that restrict reading data in Secrets (including indirect means).
  • Where appropriate, also use mechanisms such as RBAC to limit which principals are allowed to create new Secrets or replace existing ones.

But that can be not enough, and that has created room for third-party and cloud providers to provide their solution that covers these needs and at the same time also offer additional features. Some of these options are the ones shown below:

  • Cloud Key Management Systems: Pretty much all the big cloud providers provide some way of Secret Management to go beyond these features and mitigate those risks. If we talk about AWS, there is AWS Secrets Manager , if we are talking about Azure, we have Azure Key Vault , and in the case of Google, we also have Google Secret Manager.
  • Sealed Secrets is a project that tries to extend Secrets to provide more security, especially on the Configuration as a Code approach, offers a safe way to store those objects in the same kind of repositories as you expose any other Kubernetes resource file. In its own words, “ The SealedSecret can be decrypted only by the controller running in the target cluster, and nobody else (not even the original author) can obtain the original Secret from the SealedSecret.”
  • Third-party Secrets Managers that are similar to the ones from the Cloud Providers that allows a more independent approach, and there are several players here such as Hashicorp Vault or CyberArk Secret Manager
  • Finally also, Spring Cloud Config can provide security to store data that are related to sensitive configuration concepts such as passwords and at the same time covers the same need as the ConfigMap provides from a unified perspective.

I hope this article has helped to understand the purpose of the Secrets in Kubernetes and, at the same time, the risks regarding its security and how we can mitigate them or even rely on other solutions that provide a more secure way to handle this critical piece of information.

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *