Dsar SysAdmin

Servidor Linux en Producción

Implementación de un servidor Linux endurecido, monitorizado y automatizado, preparado para entornos reales de producción.

🖥️ Alcance del proyecto

Despliegue desde cero de un servidor Linux, incluyendo seguridad avanzada, servicios web, monitorización, automatización de tareas y documentación del ciclo de vida del sistema.

📡 Arquitectura general

                 +---------------------------+
                 |        Internet           |
                 +-------------+-------------+
                               |
                               v
                     +-----------------+
                     |   Reverse DNS   |
                     +--------+--------+
                              |
                              v
+-----------------------------+-----------------------------+
|                        Firewall / UFW                    |
+-----------------------------+-----------------------------+
                              |
                              v
+----------------------------------------------------------+
|                    Servidor Linux                        |
|                                                          |
|  +------------------+   +-----------------------------+  |
|  |   Seguridad      |   |        Servicios Web        |  |
|  |  - SSH seguro    |   |  - Nginx                    |  |
|  |  - Fail2ban      |   |  - Static / Reverse Proxy   |  |
|  |  - AppArmor      |   +-----------------------------+  |
|  |  - auditd        |                                   |
|  +------------------+   +-----------------------------+  |
|                          |     Monitorización         |  |
|                          |  - Prometheus node_exporter|  |
|                          |  - Netdata                 |  |
|                          |  - Logs centralizados      |  |
|                          +-----------------------------+  |
|                                                          |
|  +------------------+                                    |
|  |  Automatización  |                                    |
|  |  - Ansible       |                                    |
|  |  - Scripts Bash  |                                    |
|  +------------------+                                    |
+----------------------------------------------------------+

🔧 Configuraciones clave

1. SSH endurecido

# /etc/ssh/sshd_config
Port 2222
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers daniel
ClientAliveInterval 300
ClientAliveCountMax 2

2. Firewall UFW

$ ufw default deny incoming
$ ufw default allow outgoing
$ ufw allow 2222/tcp
$ ufw allow 80/tcp
$ ufw allow 443/tcp
$ ufw enable

3. Virtual Host en Nginx

# /etc/nginx/sites-available/dsar.es
server {
    listen 80;
    server_name dsar.es;

    root /var/www/dsar/web;
    index index.html;

    access_log /var/log/nginx/dsar_access.log;
    error_log  /var/log/nginx/dsar_error.log;

    location / {
        try_files $uri $uri/ =404;
    }
}

4. Servicio systemd personalizado

# /etc/systemd/system/backup.service
[Unit]
Description=Backup diario del servidor

[Service]
Type=oneshot
ExecStart=/usr/local/bin/backup.sh

[Install]
WantedBy=multi-user.target

📈 Monitorización (Prometheus, Netdata, logs)

Prometheus node_exporter

# Servicio node_exporter
[Unit]
Description=Prometheus Node Exporter
After=network.target

[Service]
User=nodeexp
Group=nodeexp
ExecStart=/usr/local/bin/node_exporter

[Install]
WantedBy=multi-user.target

Netdata

Netdata se utiliza para tener una vista en tiempo real de CPU, memoria, disco, red y procesos. Se limita el acceso mediante firewall y autenticación.

$ ufw allow from 192.168.1.0/24 to any port 19999

Logs centralizados

Se estructuran logs por servicio (Nginx, SSH, sistema) y se revisan periódicamente con herramientas como journalctl y rotación mediante logrotate.

$ journalctl -u nginx.service -n 50
$ tail -f /var/log/auth.log

🛡️ Seguridad avanzada

AppArmor

Se aplican perfiles AppArmor a servicios críticos para limitar sus capacidades incluso en caso de compromiso.

$ aa-status
apparmor module is loaded.
Nginx profile: /etc/apparmor.d/usr.sbin.nginx

Fail2ban

# /etc/fail2ban/jail.d/sshd.conf
[sshd]
enabled  = true
port     = 2222
filter   = sshd
logpath  = /var/log/auth.log
maxretry = 5
bantime  = 3600

auditd

Se monitorizan cambios sensibles en archivos de configuración y binarios críticos.

# /etc/audit/rules.d/audit.rules
-w /etc/ssh/sshd_config -p wa -k ssh_config_change
-w /etc/nginx/ -p wa -k nginx_config_change

🤖 Automatización (Ansible y scripts Bash)

Playbook Ansible simplificado

# playbook.yml
- hosts: servidor_produccion
  become: yes
  tasks:
    - name: Actualizar paquetes
      apt:
        update_cache: yes
        upgrade: dist

    - name: Asegurar que nginx está instalado
      apt:
        name: nginx
        state: present

    - name: Copiar configuración de nginx
      template:
        src: templates/dsar.es.j2
        dest: /etc/nginx/sites-available/dsar.es
      notify: Reload nginx

  handlers:
    - name: Reload nginx
      service:
        name: nginx
        state: reloaded

Script Bash de backup

#!/bin/bash
BACKUP_DIR="/backup/$(date +%F)"
mkdir -p "$BACKUP_DIR"

tar czf "$BACKUP_DIR/www.tar.gz" /var/www/dsar
tar czf "$BACKUP_DIR/etc.tar.gz" /etc

find /backup -type d -mtime +7 -exec rm -rf {} \;

🖥️ Capturas simuladas de consola

daniel@server:~$ systemctl status nginx
● nginx.service - A high performance web server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled)
   Active: active (running) since Tue 2026-01-12 14:22:11 CET
daniel@server:~$ sudo ufw status
Status: active

To                         Action      From
--                         ------      ----
2222/tcp                   ALLOW       Anywhere
80/tcp                     ALLOW       Anywhere
443/tcp                    ALLOW       Anywhere
19999/tcp                  ALLOW       192.168.1.0/24
daniel@server:~$ fail2ban-client status sshd
Status for the jail: sshd
|- Filter
|  `- Currently failed: 0
`- Actions
   `- Currently banned: 3

⚙️ Retos y soluciones

🔸 Reto 1: No perder acceso por firewall

Problema: Riesgo de bloquear el acceso SSH al activar UFW.

Solución: Definir reglas de SSH antes de habilitar el firewall y probar desde otra sesión.

$ ufw allow 2222/tcp
$ ufw enable

🔸 Reto 2: Permisos en /var/www y usuario www-data

Problema: Nginx no podía leer algunos archivos estáticos.

Solución: Ajustar propietario, grupo y permisos mínimos necesarios.

$ chown -R www-data:www-data /var/www/dsar
$ find /var/www/dsar -type d -exec chmod 755 {} \;
$ find /var/www/dsar -type f -exec chmod 644 {} \;

🔸 Reto 3: Repetición de tareas de mantenimiento

Solución: Playbooks Ansible y servicios systemd para backups y despliegues.

⏱️ Timeline del proyecto (estilo terminal)

[2026-01-05]  Instalación base de Linux y actualización del sistema
[2026-01-06]  Configuración de SSH, UFW y usuarios
[2026-01-07]  Despliegue de Nginx y estructura /var/www/dsar
[2026-01-08]  Integración de Prometheus node_exporter y Netdata
[2026-01-09]  Configuración de Fail2ban, AppArmor y auditd
[2026-01-10]  Automatización con Ansible y scripts de backup
[2026-01-11]  Pruebas de carga, revisión de logs y ajustes finales
[2026-01-12]  Puesta en producción

🎯 Objetivo

Diseñar y mantener un servidor Linux de producción con enfoque en seguridad, observabilidad y automatización, documentando el proceso de forma clara y reproducible.

← Volver