martes, 12 de agosto de 2025

script Post Leapp

 #!/bin/ksh


LOGFILE="/var/log/postleap_firewalld_check.log"

DATE=$(date "+%Y-%m-%d %H:%M:%S")


echo "[$DATE] --- Inicio del chequeo post-Leapp FirewallD ---" | tee -a $LOGFILE


# 1. Verificar si firewalld está activo

if systemctl is-active --quiet firewalld; then

    echo "✅ firewalld está activo." | tee -a $LOGFILE

else

    echo "⚠️  firewalld está inactivo. Se recomienda activarlo si se requiere protección a nivel red." | tee -a $LOGFILE

    read -p "¿Deseás activarlo ahora? (s/n): " ACTIVATE_FW

    if [[ "$ACTIVATE_FW" == "s" ]]; then

        systemctl enable --now firewalld

        echo "🔥 firewalld activado." | tee -a $LOGFILE

    else

        echo "⚠️  Se continúa con firewalld desactivado." | tee -a $LOGFILE

        exit 0

    fi

fi


# 2. Obtener puertos en uso por procesos (TCP y UDP)

echo "\n🔍 Buscando puertos en escucha por procesos..." | tee -a $LOGFILE

LISTEN_PORTS=$(ss -tuln | awk '/LISTEN|UNCONN/ && $5 ~ /[0-9]+$/ {split($5,a,":"); print a[length(a)]"/"$1}' | sort -u)


# 3. Obtener puertos y servicios habilitados por firewalld (zona default)

DEFAULT_ZONE=$(firewall-cmd --get-default-zone)

OPEN_PORTS=$(firewall-cmd --zone=$DEFAULT_ZONE --list-ports)

OPEN_SERVICES=$(firewall-cmd --zone=$DEFAULT_ZONE --list-services)


# 4. Comparar puertos en uso vs habilitados (incluye servicios)

echo "\n📊 Comparando puertos en uso vs habilitados en firewalld..." | tee -a $LOGFILE

PORTS_TO_ADD=""


for PORT_PROTO in $LISTEN_PORTS; do

    PORT_NUM=$(echo "$PORT_PROTO" | cut -d'/' -f1)

    PROTO=$(echo "$PORT_PROTO" | cut -d'/' -f2 | tr 'A-Z' 'a-z')


    # Chequear si el puerto está habilitado explícitamente

    echo "$OPEN_PORTS" | grep -qw "${PORT_NUM}/${PROTO}"

    if [[ $? -eq 0 ]]; then

        continue

    fi


    # Chequear si el puerto está cubierto por un servicio

    SERVICE_MATCH=0

    for SVC in $OPEN_SERVICES; do

        PORTS_SVC=$(firewall-cmd --info-service=$SVC | grep ports: | awk '{print $2}')

        echo "$PORTS_SVC" | grep -qw "${PORT_NUM}/${PROTO}" && SERVICE_MATCH=1

    done


    if [[ $SERVICE_MATCH -eq 0 ]]; then

        echo "⚠️  Puerto $PORT_NUM/$PROTO está en uso pero NO habilitado en firewalld." | tee -a $LOGFILE

        PORTS_TO_ADD="$PORTS_TO_ADD ${PORT_NUM}/${PROTO}"

    fi

done


# 5. Ofrecer agregar automáticamente los puertos detectados

if [[ -n "$PORTS_TO_ADD" ]]; then

    echo "\n🛡️  Los siguientes puertos están en uso pero no habilitados: $PORTS_TO_ADD" | tee -a $LOGFILE

    read -p "¿Querés habilitarlos automáticamente en firewalld? (s/n): " ADD_PORTS

    if [[ "$ADD_PORTS" == "s" ]]; then

        for P in $PORTS_TO_ADD; do

            firewall-cmd --zone=$DEFAULT_ZONE --permanent --add-port=$P

            echo "✅ Puerto $P habilitado." | tee -a $LOGFILE

        done

        firewall-cmd --reload

        echo "🔄 firewalld recargado con los nuevos puertos." | tee -a $LOGFILE

    else

        echo "📝 No se agregaron los puertos. Revisalos manualmente." | tee -a $LOGFILE

    fi

else

    echo "✅ Todos los puertos en uso están habilitados en firewalld o cubiertos por un servicio." | tee -a $LOGFILE

fi


# 6. Chequear servicios en estado failed

echo "\n🔍 Verificando servicios en estado FAILED..." | tee -a $LOGFILE

FAILED_SERVICES=$(systemctl -l -t service --state=failed | grep -v "0 loaded units" | grep -v "LOAD" | grep -v "UNIT")

if [[ -n "$FAILED_SERVICES" ]]; then

    echo "⚠️  Servicios en estado failed detectados:" | tee -a $LOGFILE

    echo "$FAILED_SERVICES" | tee -a $LOGFILE

else

    echo "✅ No hay servicios en estado failed." | tee -a $LOGFILE

fi


# 7. Chequear variables NEXUS

echo "\n🔍 Verificando variables de entorno NEXUS_*..." | tee -a $LOGFILE

NEXUS_VARS=$(env | grep -i ^NEXUS_)


if [[ -n "$NEXUS_VARS" ]]; then

    echo "✅ Variables NEXUS detectadas:" | tee -a $LOGFILE

    echo "$NEXUS_VARS" | tee -a $LOGFILE

else

    echo "⚠️  No se encontraron variables NEXUS_* en el entorno." | tee -a $LOGFILE

fi


echo "✅ Revisión finalizada. Verificá el log: $LOGFILE"


viernes, 8 de agosto de 2025

auditoria puntual por hora

 ---

- name: Auditoría forense con CSV consolidado y legible

  hosts: all

  gather_facts: false


  vars:

    fecha_inicio: "2025-08-01 21:00:00"

    fecha_fin: "2025-08-02 02:30:00"


  tasks:

    - name: Obtener hostname

      command: hostname

      register: hostname


    - name: Obtener historial de root

      shell: |

        cat /root/.bash_history 2>/dev/null | grep -Ei 'rm|unlink|mv|truncate'

      register: root_history

      ignore_errors: true


    - name: Obtener historial de ansible

      shell: |

        cat /home/ansible/.bash_history 2>/dev/null | grep -Ei 'rm|unlink|mv|truncate'

      register: ansible_history

      ignore_errors: true


    - name: Buscar uso de sudo por ansible en ventana temporal

      shell: |

        awk '

          BEGIN {

            start = mktime("2025 08 01 21 00 00")

            end = mktime("2025 08 02 02 30 00")

          }

          {

            cmd = "date -d \""$1" "$2" "$3" "$4"\" +%s"

            cmd | getline t

            close(cmd)

            if (t >= start && t <= end) print $0

          }

        ' /var/log/secure | grep 'sudo'

      register: sudo_usage

      ignore_errors: true


    - name: Verificar si auditd está instalado

      shell: rpm -q audit

      register: auditd_installed

      ignore_errors: true


    - name: Buscar comandos sospechosos con auditd

      when: auditd_installed.rc == 0

      shell: |

        ausearch -x rm -x unlink -x rmdir -ts "{{ fecha_inicio }}" -te "{{ fecha_fin }}"

      register: audit_logs

      ignore_errors: true


    - name: Preparar línea CSV por host (con campos entre comillas dobles)

      set_fact:

        audit_line: |

          "{{ hostname.stdout }}","{{ root_history.stdout | default('') | replace('\n', ' | ') }}","{{ ansible_history.stdout | default('') | replace('\n', ' | ') }}","{{ sudo_usage.stdout | default('') | replace('\n', ' | ') }}","{{ audit_logs.stdout | default('') | replace('\n', ' | ') }}"


    - name: Agregar cabecera si no existe (solo una vez)

      local_action:

        module: lineinfile

        path: ./auditoria_resultados.csv

        line: '"Hostname","Root History","Ansible History","Sudo Usage","Auditd Events"'

        create: yes

        insertafter: BOF

      delegate_to: localhost

      run_once: true


    - name: Agregar línea por host al CSV

      local_action:

        module: lineinfile

        path: ./auditoria_resultados.csv

        line: "{{ audit_line }}"

        create: yes

        insertafter: EOF

      delegate_to: localhost