Un blog mas

Bitácora de vuelo

Se utilizó el módulo replace para reemplazar un texto en el archivo /etc/default/grub y el módulo update-grup para actualizar los cambios.

Generar un archivo disable_ipv6.yml con el siguiente código:

---
- hosts: all
  remote_user: admin
  become: yes
  tasks:
    - name: 'Check if grub is present'
      stat: 
        path=/etc/default/grub
      register: grub_file
    - name: 'Disable IPv6 - GRUB_CMD_LINE_LINUX'
      replace:
        path: /etc/default/grub
        regexp:  '^GRUB_CMDLINE_LINUX="((:?(?!ipv6\.disable=1).)*?)"$'
        replace: 'GRUB_CMDLINE_LINUX="\1 ipv6.disable=1"'
      when: grub_file.stat.exists
      register: updateGrub
    - name: 'Disable IPv6 - GRUB_CMDLINE_LINUX_DEFAULT'
      replace:
        path: /etc/default/grub
        regexp:  '^GRUB_CMDLINE_LINUX_DEFAULT="((:?(?!ipv6\.disable=1).)*?)"$'
        replace: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 ipv6.disable=1"'
      register: updateGrub
      when: grub_file.stat.exists
    - name: 'update-grub'
      shell: update-grub
      when: updateGrub is defined

El script se ejecuta de la siguiente manera:

pablo@ansible:~$ ansible-playbook disable_ipv6.yml -K
SUDO password: 

PLAY [192.168.0.100] *******************************************************************************************************************************************************

TASK [Gathering Facts] ***************************************************************************************************************************************************
ok: [192.168.0.100]

TASK [Check if grub is present] ******************************************************************************************************************************************
ok: [192.168.0.100]

TASK [Disable IPv6 - GRUB_CMD_LINE_LINUX] **********************************************************************************************************************************************
changed: [192.168.0.100]

TASK [Disable IPv6 - GRUB_CMDLINE_LINUX_DEFAULT] **************************************************************************************************************************************
changed: [192.168.0.100]

TASK [update-grub] *******************************************************************************************************************************************************
changed: [192.168.0.100]

PLAY RECAP ***************************************************************************************************************************************************************
192.168.0.100                : ok=5    changed=3    unreachable=0    failed=0   

pablo@ansible:~$ 

Se utilizó el módulo apt para actualizar servidores con Ansible.

Se generó un archivo apt.yml con el siguiente código:

---
- hosts: all
  remote_user: admin
  become: yes
  tasks:
    - name: 'update'
      apt:
        update_cache: yes
    - name: 'upgrade'
      apt:
        name: "*"
        state: latest
    - name: 'dist-upgrade'
      apt:
        upgrade: dist
    - name: 'autoremove'
      apt:
        autoremove: yes
    - name: 'autoclean'
      apt:
        autoclean: yes

El script se ejecuta de la siguiente manera:

pablo@ansible:~$ ansible-playbook apt.yml -K  
SUDO password: 

PLAY [192.168.0.100] *****************************************************************************************************************************************************************************

TASK [Gathering Facts] **************************************************************************************************************************************************************************
ok: [192.168.0.100]

TASK [update] ***********************************************************************************************************************************************************************************
changed: [192.168.0.100]

TASK [upgrade] **********************************************************************************************************************************************************************************
changed: [192.168.0.100]

TASK [dist-upgrade] *****************************************************************************************************************************************************************************
ok: [192.168.0.100]

TASK [autoremove] *******************************************************************************************************************************************************************************
ok: [192.168.0.100]

TASK [autoclean] ********************************************************************************************************************************************************************************
ok: [192.168.0.100]

PLAY RECAP **************************************************************************************************************************************************************************************
192.168.0.100               : ok=6    changed=2    unreachable=0    failed=0   

pablo@ansible:~$ 

Se utilizaron los módulos user para crear el usuario, authorized_key para distribuir la clave pública de BackupPc y lineinfile para modificar el sudoers.

Se generó un archivo backuppcClient.yml con el siguiente código:

---
- hosts: client1
  remote_user: admin
  become: yes
  vars:
    users:
      - "backuppc"
  tasks:
    - name: create user backuppc
      user:
        name: "{{ item }}"  
        shell: /bin/bash
      with_items: "{{ users }}"
    - name: Add public key in authorized_keys'
      authorized_key:
        user: "{{ item }}"
        key: "{{ lookup('file', 'id_rsa.pub') }}"
      with_items: "{{ users }}"
    - name: Add rsync without password in sudoers
      copy:
        content: "backuppc ALL=NOPASSWD: /usr/bin/rsync --server --sender * \n"
        dest: /etc/sudoers.d/backuppc
        backup: yes
        owner: root
        group: root
        mode: 0440
        validate: /usr/sbin/visudo -cf %s


El archivo id_rsa.pub contiene la clave pública del BackupPc.

El script se ejecuta de la siguiente manera:

admin@ansible:~$ ansible-playbook backuppcClient.yml -K
SUDO password: 
PLAY [192.168.0.100] *************************************************************************************************************************************************************

TASK [Gathering Facts] **********************************************************************************************************************************************************
ok: [192.168.0.100]

TASK [Crear usuario BackupPc] **************************************************************************************************************************************************
ok: [192.168.0.100] => (item=backuppc)

TASK [Agregar clave pública al authorized_keys] **************************************************************************************************************************************************
ok: [192.168.0.100] => (item=backuppc)

TASK [Modificar archivo sudoers para ejecutar rsync sin contraseña] *************************************************************************************************************************
ok: [192.168.0.100]

PLAY RECAP **********************************************************************************************************************************************************************
192.168.0.100               : ok=4    changed=3    unreachable=0    failed=0   

admin@ansible:~$ 

Instalar los paquetes necesarios

pablo@host:~# sudo sudo apt install zfsutils-linux lxd

pablo@host:~$ sudo lxd init
Would you like to use LXD clustering? (yes/no) [default=no]: 
Do you want to configure a new storage pool? (yes/no) [default=yes]: 
Name of the new storage pool [default=default]:     
Name of the storage backend to use (dir, zfs) [default=zfs]: 
Create a new ZFS pool? (yes/no) [default=yes]: 
Would you like to use an existing block device? (yes/no) [default=no]: 
Size in GB of the new loop device (1GB minimum) [default=84GB]: 
Would you like to connect to a MAAS server? (yes/no) [default=no]: 
Would you like to create a new local network bridge? (yes/no) [default=yes]: 
What should the new bridge be called? [default=lxdbr0]: 
What IPv4 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: 
What IPv6 address should be used? (CIDR subnet notation, “auto” or “none”) [default=auto]: none
Would you like LXD to be available over the network? (yes/no) [default=no]: 
Would you like stale cached images to be updated automatically? (yes/no) [default=yes] 
Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]: 
pablo@host:~$ 

Listar las imágenes disponibles para crear un contenedor

pablo@host:~$ sudo lxc image list images:ubuntu arch=amd64
+----------------------------+--------------+--------+--------------------------------------+--------+----------+
|           ALIAS            | FINGERPRINT  | PUBLIC |             DESCRIPCIÓN              |  ARQ   |  TAMAÑO  |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/14.04 (7 más)       | 7f146839082a | sí     | Ubuntu trusty amd64 (20200426_07:42) | x86_64 | 75.45MB  |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/16.04 (7 más)       | 219cff31b8f5 | sí     | Ubuntu xenial amd64 (20200426_07:42) | x86_64 | 80.77MB  |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/16.04/cloud (3 más) | 805b76000857 | sí     | Ubuntu xenial amd64 (20200426_07:42) | x86_64 | 99.91MB  |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/18.04 (7 más)       | acf444ccf6f6 | sí     | Ubuntu bionic amd64 (20200426_08:52) | x86_64 | 94.46MB  |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/18.04/cloud (3 más) | 3d7b52c8c572 | sí     | Ubuntu bionic amd64 (20200426_07:42) | x86_64 | 105.25MB |                                           
+----------------------------+--------------+--------+--------------------------------------+--------+----------+                                           
| ubuntu/eoan (7 más)        | c347967a70de | sí     | Ubuntu eoan amd64 (20200426_07:42)   | x86_64 | 95.19MB  |
+----------------------------+--------------+--------+--------------------------------------+--------+----------+
| ubuntu/eoan/cloud (3 más)  | 8e3ea1480cb2 | sí     | Ubuntu eoan amd64 (20200426_07:42)   | x86_64 | 108.35MB |
+----------------------------+--------------+--------+--------------------------------------+--------+----------+
| ubuntu/focal (7 más)       | 751bac27ad88 | sí     | Ubuntu focal amd64 (20200426_07:42)  | x86_64 | 97.28MB  |
+----------------------------+--------------+--------+--------------------------------------+--------+----------+
| ubuntu/focal/cloud (3 más) | 96a2da7d8f24 | sí     | Ubuntu focal amd64 (20200426_07:42)  | x86_64 | 111.91MB |
+----------------------------+--------------+--------+--------------------------------------+--------+----------+

Crear un contenedor Ubuntu 18.04

pablo@host:~# sudo lxc launch ubuntu:18.04 ubuntu-lxc1
Creando ubuntu-lxc1
Iniciando ubuntu-lxc1  

Listar contenedores creados

pablo@host:~# sudo lxc list
+-------------+---------+---------------------+------+------------+-----------+
| NOMBRE      | ESTADO  |        IPV4         | IPV6 |    TIPO    | SNAPSHOTS |
+-------------+---------+---------------------+------+------------+-----------+
| ubuntu-lxc1 | RUNNING | 10.188.82.11 (eth0) |      | PERSISTENT | 0         |
+-------------+---------+---------------------+------+------------+-----------+

Transferir archivos del host al contenedor ubuntu-lxc1

pablo@host:~$ sudo lxc file push /home/pablo/.ssh/ ubuntu-lxc1/tmp/ --recursive --verbose
INFO[04-26|22:23:01] Pushing /home/pablo/.ssh to /tmp/.ssh (directory) 
INFO[04-26|22:23:01] Pushing /home/pablo/.ssh/authorized_keys to /tmp/.ssh/authorized_keys (file) 
INFO[04-26|22:23:01] Pushing /home/pablo/.ssh/id_rsa.pub to /tmp/.ssh/id_rsa.pub (file) 
INFO[04-26|22:23:01] Pushing /home/pablo/.ssh/known_hosts to /tmp/.ssh/known_hosts (file) 
pablo@host:~$   

Transferir archivos del contenedor ubuntu-lxc1 al host

pablo@host:~$ sudo lxc file pull ubuntu-lxc1/home/ubuntu/.ssh/authorized_keys /tmp/ --verbose
INFO[04-26|22:27:46] Pulling /tmp/authorized_keys from home/ubuntu/.ssh/authorized_keys (file) 
pablo@host:~$ 

ACCEDER AL CONTENEDOR ubuntu-lxc1 Y CAMBIAR LA CONTRASEÑA

pablo@host:~$ sudo lxc shell ubuntu-lxc1
mesg: ttyname failed: No such device 

root@ubuntu-lxc1:~# passwd ubuntu
Enter new UNIX password: 
Retype new UNIX password: 
passwd: password updated successfully
root@ubuntu-lxc1:~# 

DETENER EL CONTENEDOR ubuntu-lxc1 Y VERIFICAR SU ESTADO

pablo@host:~$ sudo lxc stop ubuntu-lxc1
pablo@host:~$ sudo lxc list
+-------------+---------+------+------+------------+-----------+
| NOMBRE      | ESTADO  | IPV4 | IPV6 |    TIPO    | SNAPSHOTS |
+-------------+---------+------+------+------------+-----------+
| ubuntu-lxc1 | STOPPED |      |      | PERSISTENT | 0         |
+-------------+---------+------+------+------------+-----------+
pablo@host:~$ 

Iniciar el contenedor ubuntu-lxc1 y verificar su estado

pablo@host:~$ sudo lxc start ubuntu-lxc1
pablo@host:~$ sudo lxc list 
+-------------+---------+---------------------+------+------------+-----------+
| NOMBRE      | ESTADO  |        IPV4         | IPV6 |    TIPO    | SNAPSHOTS |
+-------------+---------+---------------------+------+------------+-----------+
| ubuntu-lxc1 | RUNNING | 10.188.82.11 (eth0) |      | PERSISTENT | 0         |
+-------------+---------+---------------------+------+------------+-----------+
pablo@host:~$ 

Crear un snapshot del contenedor ubuntu-lxc1 y verificar su estado

pablo@host:~$ sudo lxc snapshot ubuntu-lxc1 usnap0
pablo@host:~$ sudo lxc list 
+-------------+---------+---------------------+------+------------+-----------+
| NOMBRE      | ESTADO  |        IPV4         | IPV6 |    TIPO    | SNAPSHOTS |
+-------------+---------+---------------------+------+------------+-----------+
| ubuntu-lxc1 | RUNNING | 10.188.82.11 (eth0) |      | PERSISTENT | 1         |
+-------------+---------+---------------------+------+------------+-----------+
pablo@host:~$ 

Verficar la informacion del contenedor ubuntu-lxc1

pablo@host:~$ sudo lxc info ubuntu-lxc1
Nombre: ubuntu-lxc1
Remote: unix://
Arquitectura: x86_64
Creación: 2020/04/26 23:35 UTC
Estado: Running
Type: persistent
Perfiles: default
PID: 16481
Ips:
  eth0: inet    10.188.82.11    veth7QXKDQ
  eth0: inet6   fe80::216:3eff:fe81:e698        veth7QXKDQ
  lo:   inet    127.0.0.1
  lo:   inet6   ::1
Resources:
  Procesos: 41
  Uso de CPU:
    Uso de CPU (en segundos): 8
  Memory usage:
    Memory (current): 100.23MB
    Memory (peak): 113.44MB
  Network usage:
    eth0:
      Bytes recibidos: 85.50kB
      Bytes enviados: 42.51kB
      Packets received: 534
      Packets sent: 346
    lo:
      Bytes recibidos: 4.47kB
      Bytes enviados: 4.47kB
      Packets received: 43
      Packets sent: 43
Snapshots:
  usnap0 (taken at 2020/04/27 01:33 UTC) (stateless)
pablo@host:~$ 

Revertir al snapshot usnap0 del contenedor ubuntu-lxc1

pablo@host:~$ sudo lxc restore ubuntu-lxc1 usnap0

Publicar y listar una imagen a partir del snapshot usnap0

pablo@host:~$ sudo sudo lxc publish ubuntu-lxc1/usnap0 --alias ubuntuImage4snap0
pablo@host:~$ sudo lxc image list 
+--------------------+--------------+--------+------------------------------------+--------+----------+                         
|     ALIAS          | FINGERPRINT  | PUBLIC |            DESCRIPCIÓN             |  ARQ   |  TAMAÑO  |
+--------------------+--------------+--------+------------------------------------+--------+----------+
| ubuntuImage4snap0  | 067b55c92737 | no     | Ubuntu 18.04 LTS server (20200407) | x86_64 | 271.56MB |
+--------------------+--------------+--------+------------------------------------+--------+----------+
pablo@host:~$ 

Crear un nuevo contenedor ubuntu4image a partir de la imagen ubuntuImage4snap0

pablo@host:~$ sudo lxc launch 067b55c92737 ubuntu4image
Creando ubuntu4image
Iniciando ubuntu4image
pablo@host:~$ sudo lxc list 
+---------------+---------+----------------------+------+------------+-----------+
|    NOMBRE     | ESTADO  |         IPV4         | IPV6 |    TIPO    | SNAPSHOTS |
+---------------+---------+----------------------+------+------------+-----------+
| ubuntu4image  | RUNNING | 10.188.82.227 (eth0) |      | PERSISTENT | 0         |
+---------------+---------+----------------------+------+------------+-----------+
| ubuntu-lxc1   | RUNNING | 10.188.82.151 (eth0) |      | PERSISTENT | 0         |
+---------------+---------+----------------------+------+------------+-----------+
pablo@host:~$ 

Eliminar un snapshot del contenedor ubuntu-lxc1 y verificar su estado

pablo@host:~$ sudo lxc delete ubuntu-lxc1/usnap0
pablo@host:~$ sudo lxc list 
+-------------+---------+---------------------+------+------------+-----------+
| NOMBRE      | ESTADO  |        IPV4         | IPV6 |    TIPO    | SNAPSHOTS |
+-------------+---------+---------------------+------+------------+-----------+
| ubuntu-lxc1 | RUNNING | 10.188.82.11 (eth0) |      | PERSISTENT | 0         |
+-------------+---------+---------------------+------+------------+-----------+
pablo@host:~$ 

Eliminar una imagen publicada en el host

pablo@host:~$ lxc image delete 067b55c92737
pablo@host:~$ 

Modificar los recursos de CPU y Memoria del contenedor ubuntu-lxc1

ubuntu@ubuntu-lxc1:~$ cat /proc/cpuinfo | grep processor | wc -l
4
ubuntu@ubuntu-lxc1:~$ free -h
              total        used        free      shared  buff/cache   available
Mem:           244M         52M        189M        172K        2.5M        191M
Swap:          975M          0B        975M
ubuntu@ubuntu-lxc1:~$ 

root@host:~# lxc config set ubuntu4pablo limits.cpu 2
root@host:~# lxc config set ubuntu4pablo limits.memory 512MB

ubuntu@ubuntu-lxc1:~$ cat /proc/cpuinfo | grep processor | wc -l
2
ubuntu@ubuntu-lxc1:~$ free -h
              total        used        free      shared  buff/cache   available
Mem:           488M         52M        433M        172K        2.5M        435M
Swap:          975M          0B        975M
ubuntu@ubuntu-lxc1:~$ 

En primer lugar debemos instalar y configurar el cliente msmtp

apt install msmtp

Creamos un archivo /etc/msmtprc y pegamos la siguiente configuración:

defaults
tls on
account default
host smtp.midominio.com
from fail2ban-noreply@midominio.com

Tomando como base los archivos de configuración de Sendmail que vienen por default en la instalación del Fail2Ban, en la carpeta action.d, reemplazamos el string de envío de correo de cada uno de los archivos sendmail por msmtp.

for FILE in /etc/fail2ban/action.d/sendmail*.conf; do cp "$FILE" "${FILE/sendmail/msmtp}"; done

sed -i 's/before = sendmail/before = msmtp/' /etc/fail2ban/action.d/msmtp*.conf

sed -i 's/after = sendmail/after = msmtp/' /etc/fail2ban/action.d/msmtp*.conf

sed -i 's/sbin\/sendmail -f <sender>/bin\/msmtp/g' /etc/fail2ban/action.d/msmtp*.conf

Completo los parámetros de configuración del msmtp, en el archivo /etc/fail2ban/action.d/msmtp-common.conf

	dest = pablo@midomino.com
	sender = fail2ban-noreply@midomino.com

Para configurar el envío de mails del Fail2Ban debemos modificar las siguientes líneas del archivo jail.local

.
destemail = pablo@midominio.com
sender = fail2ban-noreply@midominio.com
.
mta = msmtp
.
action = %(action_mwl)s
.

y modificamos el action del ssh para que notifique, en este caso es el archivo 7etc/fail2ban/jail.d/defaults-debian.conf

action = iptables[name=SSH, port=ssh, protocol=tcp] 
         msmtp-whois[name=SSH]

Resta reiniciar el servicio y deberíamos recibir las notificaciones por correo

service fail2ban restart

Stop SOPA