Diferencia entre revisiones de «Securizar Ubuntu Server»

De Wiki Castanedo.es
Ir a la navegación Ir a la búsqueda
Sin resumen de edición
Sin resumen de edición
 
(No se muestran 5 ediciones intermedias del mismo usuario)
Línea 4: Línea 4:


== Cambiar contraseña a usuario root ==
== Cambiar contraseña a usuario root ==
Todos los comandos se ejecutarán como root, a menos que se especifique lo contrario.
* Todos los comandos se ejecutarán como root, a menos que se especifique lo contrario.
<syntaxhighlight lang="Bash">sudo -i</syntaxhighlight>
<syntaxhighlight lang="Bash">sudo -i</syntaxhighlight>


Establecer contraseña para root:
* Establecer contraseña para root:
<syntaxhighlight lang="Bash">passwd root</syntaxhighlight>
<syntaxhighlight lang="Bash">passwd root</syntaxhighlight>


== Creación de nuevo usuario ==
== Creación de nuevo usuario ==
Crear un grupo para el usuario:
* Crear un grupo para el usuario:
<syntaxhighlight lang="Bash">groupadd guzman</syntaxhighlight>
<syntaxhighlight lang="Bash">groupadd guzman</syntaxhighlight>


Crear usuario para el usuario:
* Crear usuario para el usuario:
<syntaxhighlight lang="Bash">useradd -d /home/guzman -m -g guzman -s /bin/bash guzman</syntaxhighlight>
<syntaxhighlight lang="Bash">useradd -d /home/guzman -m -g guzman -s /bin/bash guzman</syntaxhighlight>


Establecer contraseña para el usuario:
* Establecer contraseña para el usuario:
<syntaxhighlight lang="Bash">passwd guzman</syntaxhighlight>
<syntaxhighlight lang="Bash">passwd guzman</syntaxhighlight>


Establecer permisos al usuario:
* Establecer permisos al usuario:
<syntaxhighlight lang="Bash">usermod -a -G adm,cdrom,sudo,dip,lxd guzman</syntaxhighlight>
<syntaxhighlight lang="Bash">usermod -a -G adm,cdrom,sudo,dip,lxd guzman</syntaxhighlight>


== Borrar usuario por defecto ==
== Borrar usuario por defecto ==
Se borran usuarios por defecto que puedan suponer un riesgo de ataques de diccionario.
* Se borran usuarios por defecto que puedan suponer un riesgo de ataques de diccionario.
<syntaxhighlight lang="Bash">userdel -r ubuntu</syntaxhighlight>
<syntaxhighlight lang="Bash">userdel -r ubuntu</syntaxhighlight>


Línea 31: Línea 31:


== Actualizar OS ==
== Actualizar OS ==
Actualizar repositorios:
* Actualizar repositorios:
<syntaxhighlight lang="Bash">apt update</syntaxhighlight>
<syntaxhighlight lang="Bash">apt update</syntaxhighlight>


Actualizar OS:
* Actualizar OS:
<syntaxhighlight lang="Bash">apt dist-upgrade</syntaxhighlight>
<syntaxhighlight lang="Bash">apt dist-upgrade</syntaxhighlight>


Borrar paquetes sin uso:
* Borrar paquetes sin uso:
<syntaxhighlight lang="Bash">apt autoremove</syntaxhighlight>
<syntaxhighlight lang="Bash">apt autoremove</syntaxhighlight>


Limpiar cachés:
* Limpiar cachés:
<syntaxhighlight lang="Bash">apt autoclean</syntaxhighlight>
<syntaxhighlight lang="Bash">apt autoclean</syntaxhighlight>


Reiniar VM:
* Reiniciar VM:
<syntaxhighlight lang="Bash">reboot</syntaxhighlight>
<syntaxhighlight lang="Bash">reboot</syntaxhighlight>


== Instalar fail2fan ==
== Instalar fail2fan ==
Instalar fail2fan para monitorizar logs y bloquear usuarios que intenten ataques de diccionario.
* Instalar fail2fan para monitorizar logs y bloquear usuarios que intenten ataques de diccionario.
<syntaxhighlight lang="Bash">apt install fail2ban</syntaxhighlight>
<syntaxhighlight lang="Bash">apt install fail2ban</syntaxhighlight>


Línea 91: Línea 91:


=== Comprobar que puedes acceder por SSH ===
=== Comprobar que puedes acceder por SSH ===
Desde otra terminal:
* Desde otra terminal:
<syntaxhighlight lang="Bash">ssh -i ~/.ssh/culturetas.net.key guzman@culturetas.net</syntaxhighlight>
<syntaxhighlight lang="Bash">ssh -i ~/.ssh/culturetas.net.key guzman@culturetas.net</syntaxhighlight>


Línea 126: Línea 126:
AcceptEnv LANG LC_*
AcceptEnv LANG LC_*
Subsystem      sftp    /usr/lib/openssh/sftp-server
Subsystem      sftp    /usr/lib/openssh/sftp-server
</syntaxhighlight>
* Desactivar acceso con contraseña:
Para desactivar el acceso con contraseña (sólo claves criptográficas) deberías bastar con la directiva: "PasswordAuthentication no".
Sin embargo, puede hacer alguna algún fichero adicional que lo contradiga:
<syntaxhighlight lang="Bash">vi /etc/ssh/sshd_config.d/50-cloud-init.conf</syntaxhighlight>
<syntaxhighlight lang="text">
#PasswordAuthentication yes
</syntaxhighlight>
</syntaxhighlight>


Línea 151: Línea 159:
[...]
[...]
</syntaxhighlight>
</syntaxhighlight>
== Configurar Firewall ==
* Añadir regla para SSH (22/tcp)
<syntaxhighlight lang="Bash">ufw allow 22/tcp</syntaxhighlight>
* Activar Firewall
<syntaxhighlight lang="Bash">ufw enable</syntaxhighlight>
* Comprobar reglas
<syntaxhighlight lang="Bash">
ufw status numbered
Status: active
    To                        Action      From
    --                        ------      ----
[ 1] 22/tcp                    ALLOW IN    Anywhere
[ 2] 22/tcp (v6)                ALLOW IN    Anywhere (v6)
</syntaxhighlight>
== Configurar configuraciones automáticas ==
Vamos a configurar el servidor para que instale automáticamente actualizaciones del OS.
* Instalar
<syntaxhighlight lang="Bash">apt install unattended-upgrades</syntaxhighlight>
* Configuración
<syntaxhighlight lang="Bash">vi /etc/apt/apt.conf.d/10periodic</syntaxhighlight>
<syntaxhighlight lang="text">
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";
</syntaxhighlight>
== Configurar sudo sin contraseña ==
<syntaxhighlight lang="Bash">vi /etc/sudoers.d/90-cloud-init-users</syntaxhighlight>
<syntaxhighlight lang="text">
# User rules for guzman
guzman ALL=(ALL) NOPASSWD:ALL
</syntaxhighlight>
== Configurar mensaje de bienvenida ==
* Añadir mensaje personalizado:
<syntaxhighlight lang="Bash">vi /etc/update-motd.d/00-header</syntaxhighlight>
<syntaxhighlight lang="text">
#printf "Welcome to %s (%s %s %s)\n" "$DISTRIB_DESCRIPTION" "$(uname -o)" "$(uname -r)" "$(uname -m)"
printf "WELCOME TO WEB SERVER:\n"
printf " ██████╗██╗  ██╗██╗  ████████╗██╗  ██╗██████╗ ███████╗████████╗ █████╗ ███████╗\n"
printf "██╔════╝██║  ██║██║  ╚══██╔══╝██║  ██║██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔════╝\n"
printf "██║    ██║  ██║██║    ██║  ██║  ██║██████╔╝█████╗    ██║  ███████║███████╗\n"
printf "██║    ██║  ██║██║    ██║  ██║  ██║██╔══██╗██╔══╝    ██║  ██╔══██║╚════██║\n"
printf "╚██████╗╚██████╔╝███████╗██║  ╚██████╔╝██║  ██║███████╗  ██║  ██║  ██║███████║\n"
printf " ╚═════╝ ╚═════╝ ╚══════╝╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝  ╚═╝  ╚═╝  ╚═╝╚══════╝\n"
printf "                                                        Get out of here bastad!!!\n"
</syntaxhighlight>
Nota: puedes usar un generador de ASCI Art como [https://patorjk.com/software/taag/#p=display&f=ANSI+Shadow&t=CULTURETAS&x=none&v=4&h=4&w=80&we=false Patorjk].
* Quitar mensajes innesarios:
<syntaxhighlight lang="Bash">vi /etc/update-motd.d/10-help-text</syntaxhighlight>
<syntaxhighlight lang="text">
#printf "\n"
#printf " * Documentation:  https://help.ubuntu.com\n"
#printf " * Management:    https://landscape.canonical.com\n"
#printf " * Support:        https://ubuntu.com/pro\n"
</syntaxhighlight>
* Deshabilitar noticias
<syntaxhighlight lang="Bash">vi /etc/update-motd.d/50-motd-news</syntaxhighlight>
<syntaxhighlight lang="text">
# Exit immediately, unless we're enabled
# This makes this script very easy to disable in /etc/default/motd-news configuration
[ "$ENABLED" = "0" ] || exit 0
</syntaxhighlight>
[[Categoría:Notas]]

Revisión actual - 22:16 22 feb 2026

Securizar servidor con Ubuntu Server

El objetivo de esta nota es securizar un servidor con el sistema operativo Ubuntu Server.


Cambiar contraseña a usuario root

  • Todos los comandos se ejecutarán como root, a menos que se especifique lo contrario.
sudo -i
  • Establecer contraseña para root:
passwd root

Creación de nuevo usuario

  • Crear un grupo para el usuario:
groupadd guzman
  • Crear usuario para el usuario:
useradd -d /home/guzman -m -g guzman -s /bin/bash guzman
  • Establecer contraseña para el usuario:
passwd guzman
  • Establecer permisos al usuario:
usermod -a -G adm,cdrom,sudo,dip,lxd guzman

Borrar usuario por defecto

  • Se borran usuarios por defecto que puedan suponer un riesgo de ataques de diccionario.
userdel -r ubuntu

Cambiar hostname del servidor

hostnamectl set-hostname culturetas.net

Actualizar OS

  • Actualizar repositorios:
apt update
  • Actualizar OS:
apt dist-upgrade
  • Borrar paquetes sin uso:
apt autoremove
  • Limpiar cachés:
apt autoclean
  • Reiniciar VM:
reboot

Instalar fail2fan

  • Instalar fail2fan para monitorizar logs y bloquear usuarios que intenten ataques de diccionario.
apt install fail2ban

Generar claves criptográficas

Generar clave

Características:

  • Tipo: Curva Elíptica
  • Curva: ed25519
  • Rondas: 512
ssh-keygen -t ed25519 -a 512 -C culturetas.net -f culturetas.net.key

Desplegar clave en usuario root

mkdir ~/.ssh
cp culturetas.net.key culturetas.net.key.pub /root/.ssh/
cat culturetas.net.key.pub >> /root/.ssh/authorized_keys
chmod 700 /root/.ssh/
chmod 600 /root/.ssh/culturetas.net.key
chmod 644 /root/.ssh/culturetas.net.key.pub
chmod 600 /root/.ssh/authorized_keys
chown -R root:root /root/.ssh/

Desplegar clave en usuario guzman

mkdir /home/guzman/.ssh
cp culturetas.net.key culturetas.net.key.pub /home/guzman/.ssh/
cat culturetas.net.key.pub >> /home/guzman/.ssh/authorized_keys
chmod 700 /home/guzman/.ssh/
chmod 600 /home/guzman/.ssh/culturetas.net.key
chmod 644 /home/guzman/.ssh/culturetas.net.key.pub
chmod 600 /home/guzman/.ssh/authorized_keys
chown -R guzman:guzman /home/guzman/.ssh/

Crear grupo SSHallow

Este será el único grupo que puede conectar por SSH.

groupadd -r SSHallow

Añadir usuarios a grupo SSHallow

Realizar para todos los usuarios que van a conectar mediante SSH. Por ejemplo:

  • root
  • guzman
usermod -a -G SSHallow guzman
usermod -a -G SSHallow root

Comprobar que puedes acceder por SSH

  • Desde otra terminal:
ssh -i ~/.ssh/culturetas.net.key guzman@culturetas.net

Configurar servidor SSH

  • Backup fichero de configuració SSH:
cp -a /etc/ssh/sshd_config /etc/ssh/sshd_config.$(date +%Y%m%d)
  • Editar fichero de configuración SSH:
vi /etc/ssh/sshd_config
Include /etc/ssh/sshd_config.d/*.conf
Port 22
AddressFamily any
ListenAddress 0.0.0.0
ListenAddress ::
LoginGraceTime 2m
PermitRootLogin no
StrictModes yes
MaxAuthTries 3
MaxSessions 10
PubkeyAuthentication yes
AuthorizedKeysFile      .ssh/authorized_keys .ssh/authorized_keys2
PasswordAuthentication no
PermitEmptyPasswords no
AllowGroups SSHallow
KbdInteractiveAuthentication no
UsePAM yes
X11Forwarding yes
PrintMotd no
TCPKeepAlive yes
# Timeout 300 seg * 12 = 1 hour
ClientAliveInterval 300
ClientAliveCountMax 12
AcceptEnv LANG LC_*
Subsystem       sftp    /usr/lib/openssh/sftp-server
  • Desactivar acceso con contraseña:

Para desactivar el acceso con contraseña (sólo claves criptográficas) deberías bastar con la directiva: "PasswordAuthentication no". Sin embargo, puede hacer alguna algún fichero adicional que lo contradiga:

vi /etc/ssh/sshd_config.d/50-cloud-init.conf
#PasswordAuthentication yes

Reiniciar VM

reboot

Personalizar alias

  • Manias mías
vi /root/.bashrc
[...]
# some more ls aliases
alias ll='ls -lh'
alias la='ls -A'
alias l='ls -CF'
[...]
vi /home/guzman/.bashrc
[...]
# some more ls aliases
alias ll='ls -lh'
alias la='ls -A'
alias l='ls -CF'
[...]

Configurar Firewall

  • Añadir regla para SSH (22/tcp)
ufw allow 22/tcp
  • Activar Firewall
ufw enable
  • Comprobar reglas
ufw status numbered
Status: active

     To                         Action      From
     --                         ------      ----
[ 1] 22/tcp                     ALLOW IN    Anywhere
[ 2] 22/tcp (v6)                ALLOW IN    Anywhere (v6)

Configurar configuraciones automáticas

Vamos a configurar el servidor para que instale automáticamente actualizaciones del OS.

  • Instalar
apt install unattended-upgrades
  • Configuración
vi /etc/apt/apt.conf.d/10periodic
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";

Configurar sudo sin contraseña

vi /etc/sudoers.d/90-cloud-init-users
# User rules for guzman
guzman ALL=(ALL) NOPASSWD:ALL

Configurar mensaje de bienvenida

  • Añadir mensaje personalizado:
vi /etc/update-motd.d/00-header
#printf "Welcome to %s (%s %s %s)\n" "$DISTRIB_DESCRIPTION" "$(uname -o)" "$(uname -r)" "$(uname -m)"
printf "WELCOME TO WEB SERVER:\n"
printf " ██████╗██╗   ██╗██╗  ████████╗██╗   ██╗██████╗ ███████╗████████╗ █████╗ ███████╗\n"
printf "██╔════╝██║   ██║██║  ╚══██╔══╝██║   ██║██╔══██╗██╔════╝╚══██╔══╝██╔══██╗██╔════╝\n"
printf "██║     ██║   ██║██║     ██║   ██║   ██║██████╔╝█████╗     ██║   ███████║███████╗\n"
printf "██║     ██║   ██║██║     ██║   ██║   ██║██╔══██╗██╔══╝     ██║   ██╔══██║╚════██║\n"
printf "╚██████╗╚██████╔╝███████╗██║   ╚██████╔╝██║  ██║███████╗   ██║   ██║  ██║███████║\n"
printf " ╚═════╝ ╚═════╝ ╚══════╝╚═╝    ╚═════╝ ╚═╝  ╚═╝╚══════╝   ╚═╝   ╚═╝  ╚═╝╚══════╝\n"
printf "                                                        Get out of here bastad!!!\n"

Nota: puedes usar un generador de ASCI Art como Patorjk.

  • Quitar mensajes innesarios:
vi /etc/update-motd.d/10-help-text
#printf "\n"
#printf " * Documentation:  https://help.ubuntu.com\n"
#printf " * Management:     https://landscape.canonical.com\n"
#printf " * Support:        https://ubuntu.com/pro\n"
  • Deshabilitar noticias
vi /etc/update-motd.d/50-motd-news
# Exit immediately, unless we're enabled
# This makes this script very easy to disable in /etc/default/motd-news configuration
[ "$ENABLED" = "0" ] || exit 0