#!/bin/bash #Script : sops_rules.sh #Apps : MRDEVS TOOLS #Description : Genera archivo .sops.yaml para encriptación con GPG #Author : Cortana Rosero One #Generated : Created by Claude Code (claude-3-7-sonnet-20250219) #Created : 2025/04/06 21:45:00 #Modified : 2025/04/06 21:45:00 #Version : 1.0.0 #Use Notes : ./sops_rules.sh #============================================================================== # Derechos de Autor 2025 Mauro Rosero P. #============================================================================== # Este programa es software libre: usted puede redistribuirlo y/o modificarlo # bajo los términos de la Licencia Pública Affero General de GNU tal como # lo publica la Free Software Foundation, ya sea la versión 3 de la licencia, # o (a su elección) cualquier versión posterior. # # Este programa se distribuye con la esperanza de que sea útil, # pero SIN NINGUNA GARANTÍA; sin siquiera la garantía implícita de # COMERCIABILIDAD o IDONEIDAD PARA UN PROPÓSITO PARTICULAR. Consulte la # Licencia Pública Affero General de GNU para obtener más detalles. # # Debería haber recibido una copia de la Licencia Pública Affero General # junto con este programa. Si no la recibió, consulte . # Configuración inicial SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" BIN_BASE="bin" BIN_LIBS="lib" BIN_MESG="msg" BIN_CFGS="config" # Leer DEVSPATH desde el archivo de configuración o usar "devs" por defecto if [ -f "$SCRIPT_DIR/$BIN_CFGS/devspath.dat" ]; then DEVSPATH=$(cat "$SCRIPT_DIR/$BIN_CFGS/devspath.dat") else DEVSPATH="devs" fi BIN_HOME="$HOME/$DEVSPATH" VERSION=$(cat "$SCRIPT_DIR/$BIN_CFGS/version") # CHECK SHELL LANGUAGE BIN_LANG=${LANG:0:2} # Importar bibliotecas necesarias source "${BIN_HOME}/${BIN_BASE}/${BIN_LIBS}/base.lib" source "${BIN_HOME}/${BIN_BASE}/${BIN_LIBS}/console.lib" # Cargar mensajes en el idioma del sistema o español por defecto load_messages "${BIN_HOME}/${BIN_BASE}" "${BIN_MESG}" "${BIN_LANG}" "head" title="${head_000} ${head_002}" # Verificar que gum esté instalado command_installed gum if [ $? -ne 0 ]; then echo "Error: gum no está instalado. Ejecutando bootstrap.sh..." "${BIN_HOME}/${BIN_BASE}/bootstrap.sh" # Verificar nuevamente command_installed gum if [ $? -ne 0 ]; then echo "Error: No se pudo instalar gum. Abortando." exit 1 fi fi # Verificar que GPG esté instalado command_installed gpg if [ $? -ne 0 ]; then echo "Error: gpg no está instalado. Instalando GPG..." os_pkgs_install gnupg # Verificar nuevamente command_installed gpg if [ $? -ne 0 ]; then echo "Error: No se pudo instalar GPG. Abortando." exit 1 fi fi # Verificar que SOPS esté instalado command_installed sops if [ $? -ne 0 ]; then echo "Error: sops no está instalado. Instalando SOPS..." "${BIN_HOME}/${BIN_BASE}/bootstrap.sh" # Verificar nuevamente command_installed sops if [ $? -ne 0 ]; then echo "Error: No se pudo instalar SOPS. Abortando." exit 1 fi fi # Función para validar fingerprint GPG validate_fingerprint() { local fp=$1 # Verificar que no esté vacío if [ -z "$fp" ]; then return 1 fi # Verificar longitud (40 caracteres para fingerprint completo) if [ ${#fp} -ne 40 ]; then return 2 fi # Verificar formato (hexadecimal) if ! [[ $fp =~ ^[A-Fa-f0-9]+$ ]]; then return 3 fi # Verificar si existe en el keyring if ! gpg --list-keys "$fp" &>/dev/null; then return 4 fi return 0 } # Función para obtener las claves GPG disponibles get_available_keys() { gpg --list-keys --with-colons | grep -E "^pub" | awk -F: '{print $5}' } # Función para mostrar un error y esperar confirmación show_error() { gum style --foreground "#FF0000" --bold "$1" gum input --placeholder "Presiona Enter para continuar..." } # Función para obtener información de la clave get_key_info() { local fingerprint=$1 local key_info=$(gpg --list-keys --with-colons "$fingerprint") local user_id=$(echo "$key_info" | grep -E "^uid" | head -n 1 | awk -F: '{print $10}') echo "$user_id" } # Ruta donde se creará el archivo .sops.yaml SOPS_CONFIG="$BIN_HOME/.sops.yaml" # Verificar si el archivo ya existe if [ -f "$SOPS_CONFIG" ]; then if ! gum confirm "El archivo $SOPS_CONFIG ya existe. ¿Desea sobrescribirlo?"; then echo "Operación cancelada por el usuario." exit 0 fi fi # Mostrar título echo gum style --foreground 212 --bold --align center "Configuración de SOPS PGP para Encriptación" echo # Buscar claves disponibles echo "Buscando claves GPG disponibles..." AVAILABLE_KEYS=($(get_available_keys)) if [ ${#AVAILABLE_KEYS[@]} -eq 0 ]; then show_error "No se encontraron claves GPG. Por favor, genere o importe una clave GPG primero." exit 1 fi # Mostrar información y permitir selección echo gum style --foreground "#00AAFF" "Claves GPG disponibles:" echo KEY_OPTIONS=() for key in "${AVAILABLE_KEYS[@]}"; do key_info=$(get_key_info "$key") KEY_OPTIONS+=("$key ($key_info)") done SELECTED_KEY_FULL=$(gum choose "${KEY_OPTIONS[@]}") SELECTED_KEY=$(echo "$SELECTED_KEY_FULL" | awk '{print $1}') # Validar la selección if [ -z "$SELECTED_KEY" ]; then echo "No se seleccionó ninguna clave. Operación cancelada." exit 1 fi validate_fingerprint "$SELECTED_KEY" VALIDATION_RESULT=$? if [ $VALIDATION_RESULT -ne 0 ]; then case $VALIDATION_RESULT in 1) show_error "Error: El fingerprint está vacío." ;; 2) show_error "Error: El fingerprint debe tener 40 caracteres de longitud." ;; 3) show_error "Error: El fingerprint debe contener solo caracteres hexadecimales (A-F, 0-9)." ;; 4) show_error "Error: La clave con fingerprint $SELECTED_KEY no se encuentra en el keyring GPG." ;; *) show_error "Error de validación desconocido." ;; esac exit 1 fi # Confirmar la selección echo gum style --foreground "#00FF00" "Se utilizará la siguiente clave para encriptación SOPS:" gum style "Fingerprint: $SELECTED_KEY" gum style "Usuario: $(get_key_info "$SELECTED_KEY")" echo if ! gum confirm "¿Confirma esta selección?"; then echo "Operación cancelada por el usuario." exit 0 fi # Crear el archivo .sops.yaml echo "Generando archivo de configuración SOPS..." cat > "$SOPS_CONFIG" << EOF creation_rules: - pgp: '$SELECTED_KEY' EOF # Verificar que el archivo se haya creado correctamente if [ $? -eq 0 ] && [ -f "$SOPS_CONFIG" ]; then gum style --foreground "#00FF00" --bold "✅ Archivo .sops.yaml creado exitosamente en $SOPS_CONFIG" gum style "Esta configuración se utilizará para encriptar/desencriptar archivos con SOPS" gum style "utilizando la clave GPG seleccionada." echo gum style --foreground "#FFAA00" "Ejemplo de uso:" gum style "sops --encrypt archivo.json > archivo.sops.json" gum style "sops --decrypt archivo.sops.json > archivo.json" else show_error "❌ Error al crear el archivo de configuración SOPS." exit 1 fi