feat: añadido archivos básicos para crear el template y los equipos en proxmox

This commit is contained in:
Javier Niño Sánchez
2026-10-25 20:02:54 +01:00
parent a02ff5c4bc
commit 2f17d7b03d
8 changed files with 501 additions and 1 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
state/

188
README.md
View File

@@ -1,3 +1,189 @@
# bash-101-resources
Materiales utilizados para el taller de bash celebrado por el ETSIIT Tech Club el miércoles 29 de octubre
Materiales utilizados para el taller de bash celebrado por el ETSIIT Tech Club el miércoles 29 de octubre.
Cada equipo tiene un contenedor LXC en Proxmox con una terminal web (ttyd), los retos por niveles y un marcador en vivo. Los scripts cubren lo que se repite por equipo o se ejecuta durante el evento; lo que se hace una sola vez está aquí abajo como notas. El diseño completo está en [PLAN.md](PLAN.md).
| Máquina | Dirección |
|---|---|
| Sobremesa (`virbr-taller`) | 192.168.150.1 |
| Host Proxmox (`vmbr0`) | 192.168.150.2 |
| CT proxy (199) | 192.168.150.10 en `eth0` (`vmbr0`), 10.10.10.1 en `eth1` (`vmbr1`) |
| CT del equipo n | 10.10.10.(100+n), solo en `vmbr1` |
## Montaje
### 1. VM en el sobremesa
Red de libvirt propia en modo `open`, en la que libvirt no pone reglas de firewall. En la red `default` (NAT), la cadena `guest_input` de libvirt rechaza toda conexión nueva hacia la VM, también las que llegan por DNAT, así que el paso 4 no funcionaría.
```sh
export LIBVIRT_DEFAULT_URI=qemu:///system
cat > taller-net.xml <<'EOF'
<network>
<name>taller</name>
<forward mode='open'/>
<bridge name='virbr-taller'/>
<ip address='192.168.150.1' netmask='255.255.255.0'>
<dhcp><range start='192.168.150.100' end='192.168.150.199'/></dhcp>
</ip>
</network>
EOF
virsh net-define taller-net.xml && virsh net-autostart taller && virsh net-start taller
virt-install --name pve --osinfo debian13 \
--vcpus 10 --cpu host-passthrough \
--memory 16384 --memballoon none \
--controller type=scsi,model=virtio-scsi \
--disk size=32,bus=scsi,cache=none,discard=unmap \
--disk size=40,format=raw,bus=scsi,cache=none,discard=unmap \
--network network=taller,model=virtio \
--cdrom proxmox-ve_9.*.iso
```
En el instalador: sistema en `sda`, IP `192.168.150.2/24`, puerta de enlace y DNS `192.168.150.1`. `sdb` se queda vacío para ZFS.
### 2. Proxmox
```sh
# Repositorio no-subscription
rm -f /etc/apt/sources.list.d/{pve-enterprise,ceph}.sources
cat > /etc/apt/sources.list.d/proxmox.sources <<'EOF'
Types: deb
URIs: http://download.proxmox.com/debian/pve
Suites: trixie
Components: pve-no-subscription
Signed-By: /usr/share/keyrings/proxmox-archive-keyring.gpg
EOF
apt update && apt full-upgrade -y
apt install -y curl qrencode # template.sh y teams.sh
# Pool ZFS en el segundo disco (compruébalo con lsblk)
zpool create -o ashift=12 -o autotrim=on -O compression=lz4 -O atime=off tank /dev/sdb
pvesm add zfspool tank --pool tank --content rootdir,images
# ARC limitado a 4 GiB, ya y tras reiniciar
echo "options zfs zfs_arc_max=$((4 << 30))" > /etc/modprobe.d/zfs.conf
update-initramfs -u -k all
echo $((4 << 30)) > /sys/module/zfs/parameters/zfs_arc_max
```
### 3. Red interna y firewall
```sh
# Bridge sin puertos ni IP; el segundo comando aplica la configuración
pvesh create /nodes/"$(hostname)"/network --iface vmbr1 --type bridge --autostart 1
pvesh set /nodes/"$(hostname)"/network
pvesh set /cluster/firewall/options --enable 1
pvesh set /nodes/"$(hostname)"/firewall/options --enable 1
```
Las reglas por defecto mantienen SSH y la GUI accesibles desde la red local (192.168.150.0/24). Si entras desde otra red, añade tu IP al ipset `management` antes de activar el firewall.
### 4. DNAT en el sobremesa
Va antes que el proxy porque certbot necesita el puerto 80 accesible desde fuera. El router tiene que reenviar 80 y 443 al sobremesa, y `DOMAIN` (en `common.sh`) tiene que resolver a la IP pública.
`taller.nft` (ajusta `WAN` a la interfaz del sobremesa hacia el router):
```nft
define WAN = "enp5s0"
define PROXY = 192.168.150.10
table ip taller
delete table ip taller
table ip taller {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
iifname $WAN tcp dport { 80, 443 } dnat to $PROXY
}
chain postrouting {
type nat hook postrouting priority srcnat; policy accept;
ip saddr 192.168.150.0/24 oifname $WAN masquerade
}
chain forward {
type filter hook forward priority filter; policy accept;
oifname "virbr-taller" ct state established,related accept
oifname "virbr-taller" ct status dnat accept
oifname "virbr-taller" drop
}
}
```
```sh
sudo sysctl -w net.ipv4.ip_forward=1
sudo nft -f taller.nft # recargable; no persiste tras reiniciar
sudo nft delete table ip taller # al acabar
```
El masquerade da salida a internet a la VM, porque el modo `open` no hace NAT. Si el sobremesa ya tiene un ruleset con `policy drop` en `input` o `forward`, ahí también hay que dejar pasar el DHCP y el DNS de `virbr-taller` (UDP 67 y 53) y el tráfico reenviado hacia y desde `virbr-taller`: un `drop` en cualquier tabla es definitivo.
### 5. CT proxy
```sh
pveam update
img=$(pveam available --section system | awk '/debian-13-standard_.*_amd64\./ { print $2 }' | sort -V | tail -n 1)
pveam download local "$img"
pct create 199 "local:vztmpl/$img" \
--hostname proxy --unprivileged 1 --features nesting=1 --onboot 1 \
--rootfs tank:4 \
--net0 name=eth0,bridge=vmbr0,ip=192.168.150.10/24,gw=192.168.150.1 \
--net1 name=eth1,bridge=vmbr1,ip=10.10.10.1/24
pct start 199
pct enter 199
```
Dentro del proxy:
```sh
apt update && apt install -y nginx certbot
# El sitio por defecto ya sirve /var/www/html en el 80
certbot certonly --webroot -w /var/www/html -d taller.example.org \
-m organizacion@example.org --agree-tos --deploy-hook 'systemctl reload nginx'
touch /etc/nginx/taller-routes.conf # lo rellena teams.sh; nginx -t falla si no existe
cat > /etc/nginx/sites-available/taller <<'EOF'
server {
listen 80;
server_name taller.example.org;
location /.well-known/acme-challenge/ { root /var/www/html; }
location / { return 301 https://$host$request_uri; }
}
server {
listen 443 ssl;
server_name taller.example.org;
ssl_certificate /etc/letsencrypt/live/taller.example.org/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/taller.example.org/privkey.pem;
include /etc/nginx/taller-routes.conf;
location / { return 404; }
}
EOF
ln -s ../sites-available/taller /etc/nginx/sites-enabled/taller
rm /etc/nginx/sites-enabled/default
nginx -t && systemctl reload nginx
```
### 6. Plantilla, equipos y evento
En el host Proxmox, con el repositorio copiado (`rsync -a --exclude .git ./ root@192.168.150.2:taller/`) y `DOMAIN` ajustado en `common.sh`:
```sh
./template.sh # CT 900, plantilla; descarga ttyd y la imagen de Debian 13
./teams.sh # CT 101-115, rutas de nginx y state/papelitos.html para imprimir
```
`./teams.sh 4` levanta solo los equipos 1 a 4 (para pruebas). `teams.sh` se puede repetir: salta los CT que ya existen y cada equipo conserva su token (y su papelito) aunque se recree su CT. Comprobación rápida:
```sh
# Abre en el navegador la URL de un papelito. Los CT no se ven entre sí:
pct exec 101 -- timeout 3 bash -c 'echo > /dev/tcp/10.10.10.102/7681' && echo MAL || echo bien
```
El día del evento:
```sh
./event.sh board
```

39
common.sh Normal file
View File

@@ -0,0 +1,39 @@
# shellcheck shell=bash disable=SC2034
# Ajustes y funciones comunes a los scripts que se ejecutan en el host Proxmox.
# No se ejecuta: cada script lo carga con source.
TEMPLATE_ID=900
PROXY_ID=199
CT_ID_BASE=100 # equipo n -> CT 100+n
CT_COUNT=15
SUBNET=10.10.10 # IP del CT de equipo = SUBNET.<id del CT>
PROXY_INT_IP=10.10.10.1
INT_BRIDGE=vmbr1
CT_CPULIMIT=0.5
CT_MEMORY_MB=512
CT_PIDS_MAX=256
CT_RATE_MBYTES=6.25 # PVE limita en MB/s: 6.25 = 50 Mbit/s
DOMAIN=taller.example.org
TTYD_PORT=7681
EXT_BRIDGE=vmbr0 # bridge con internet; solo para construir la plantilla
CT_STORAGE=tank # almacenamiento ZFS para los discos de los CT
CT_DISK_GB=4
IMAGE_STORAGE=local # almacenamiento de la imagen de Debian descargada
TTYD_VERSION=1.7.7 # binario estático oficial: Debian 13 no empaqueta ttyd
TTYD_SHA256=8a217c968aba172e0dbf3f34447218dc015bc4d5e59bf51db2f2cd12b7be4f55
die() {
echo "error: $*" >&2
exit 1
}
# Repite un comando cada segundo hasta que funcione, como mucho <tries> veces
wait_for() {
local tries=$1
shift
until "$@"; do
(( --tries > 0 )) || return 1
sleep 1
done
}

34
files/LEEME Normal file
View File

@@ -0,0 +1,34 @@
TALLER DE BASH
==============
Esta terminal es de vuestro equipo durante todo el taller: un contenedor
Linux solo para vosotros, sin internet y sin sudo.
Cómo funciona
-------------
1. Escribid el nombre del equipo en el fichero ~/equipo, en una sola línea
(por ejemplo con: nano ~/equipo). Saldrá en el marcador, así que
máximo 24 caracteres. Con eso ya tenéis el nivel 0.
2. Los retos están en ~/retos, un directorio por nivel. Cada uno tiene su
ENUNCIADO.md: less ~/retos/1-logs/ENUNCIADO.md (q para salir)
3. El marcador corrige solo, cada poco, mirando vuestros ficheros. No hay
que avisar a nadie: si está bien, sube.
4. Con los mismos puntos va delante quien llegó antes a esa puntuación.
5. Punto extra si los scripts que entreguéis pasan shellcheck sin avisos.
Reglas
------
- Dentro de vuestro contenedor todo vale: probad, romped y arreglad.
- No vale atacar el marcador, la red ni a otros equipos.
- Hay límites de CPU, memoria y procesos: una fork bomb solo os tumba
a vosotros.
- Si rompéis algo sin arreglo, pedid a la organización que reinicie el
contenedor. Vuelve al estado inicial y se pierde todo lo hecho.
Trucos
------
- man <comando> y <comando> --help responden casi todo.
- Tab autocompleta, Ctrl+R busca en el historial y Ctrl+C corta lo que
esté corriendo.
- Podéis abrir vuestra dirección en hasta 4 pestañas a la vez; cada una
es una terminal nueva.

1
files/inputrc Normal file
View File

@@ -0,0 +1 @@
$include /etc/inputrc

22
files/ttyd.service Normal file
View File

@@ -0,0 +1,22 @@
[Unit]
Description=Terminal web del equipo
# -i eth0 necesita la IP ya puesta. La pone ifupdown2, que en la imagen
# Debian 13 de PVE no retrasa network-online.target, así que se le espera a él
After=networking.service
# teams.sh escribe la ruta de la URL del equipo; hasta entonces ttyd no arranca
ConditionPathExists=/etc/default/ttyd
# Corre como alumno, que puede matarlo: reiniciarlo siempre, sin límite
StartLimitIntervalSec=0
[Service]
User=alumno
WorkingDirectory=~
Environment=LANG=C.UTF-8
EnvironmentFile=/etc/default/ttyd
# Sin NoNewPrivileges=: crontab(1) es setgid y el nivel 2b lo necesita
ExecStart=/usr/local/bin/ttyd -W -i eth0 -p ${TTYD_PORT} -b ${TTYD_BASE} -m 4 -t fontSize=16 bash -l
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target

143
teams.sh Executable file
View File

@@ -0,0 +1,143 @@
#!/usr/bin/env bash
# Se ejecuta en: host Proxmox, después de template.sh.
# Uso: ./teams.sh [n] (equipos 1..n; por defecto CT_COUNT)
# Clona un CT por equipo, lo aísla con el firewall de PVE y le da una URL
# secreta. Después publica las rutas de nginx en el proxy y deja en state/ los
# QR y los papelitos para imprimir. Se puede repetir: salta los CT que ya
# existen, y un equipo conserva su token aunque se recree su CT.
set -euo pipefail
cd "$(dirname "$0")"
# shellcheck source=SCRIPTDIR/common.sh
source ./common.sh
TOKENS=state/tokens.tsv
count=${1:-$CT_COUNT}
[[ $count =~ ^[1-9][0-9]*$ ]] || die "uso: ./teams.sh [n] (n: número de equipos, por defecto $CT_COUNT)"
token_of() {
awk -F '\t' -v id="$1" '$1 == id { print $2 }' "$TOKENS"
}
create_team() {
local n=$1 id=$((CT_ID_BASE + $1)) token
pct clone "$TEMPLATE_ID" "$id" --hostname "eq$n"
pct set "$id" --cores 1 --cpulimit "$CT_CPULIMIT" --memory "$CT_MEMORY_MB" --swap 0 \
--onboot 1 \
--net0 "name=eth0,bridge=$INT_BRIDGE,ip=$SUBNET.$id/24,rate=$CT_RATE_MBYTES,firewall=1"
echo "lxc.cgroup2.pids.max: $CT_PIDS_MAX" >> "/etc/pve/lxc/$id.conf"
# Solo el proxy puede llegar a ttyd, y no sale nada
cat > "/etc/pve/firewall/$id.fw" <<EOF
[OPTIONS]
enable: 1
policy_in: DROP
policy_out: DROP
ipfilter: 1
[RULES]
IN ACCEPT -source $PROXY_INT_IP -p tcp -dport $TTYD_PORT
EOF
pct start "$id"
# systemctl dentro del CT solo responde cuando su systemd ya ha arrancado
wait_for 30 pct exec "$id" -- systemctl is-active --quiet multi-user.target ||
die "el CT $id no ha terminado de arrancar"
token=$(token_of "$id")
if [[ -z $token ]]; then
token=$(openssl rand -hex 4)
printf '%s\t%s\n' "$id" "$token" >> "$TOKENS"
fi
printf 'TTYD_PORT=%s\nTTYD_BASE=/t/%s\n' "$TTYD_PORT" "$token" |
pct exec "$id" -- tee /etc/default/ttyd >/dev/null
pct exec "$id" -- systemctl restart ttyd
pct snapshot "$id" clean
}
# El token de la ruta es la única credencial. proxy_pass sin URI reenvía
# /t/<token>/ tal cual, que es la ruta base que espera ttyd
write_routes() {
local id token
while IFS=$'\t' read -r id token; do
cat <<EOF
location /t/$token/ {
proxy_pass http://$SUBNET.$id:$TTYD_PORT;
proxy_http_version 1.1;
proxy_set_header Upgrade \$http_upgrade;
proxy_set_header Connection "upgrade";
proxy_read_timeout 2h;
}
EOF
done < "$TOKENS"
}
# Los QR van incrustados para que el HTML se pueda imprimir por sí solo
write_slips() {
local id token n url qr
cat <<'EOF'
<!doctype html>
<html lang="es">
<head>
<meta charset="utf-8">
<title>Taller de bash: papelitos</title>
<style>
@page { size: A4; margin: 10mm; }
body { margin: 0; font-family: sans-serif; display: flex; flex-wrap: wrap; }
.slip { box-sizing: border-box; width: 50%; height: 90mm; padding: 6mm;
border: 1px dashed #999; text-align: center; break-inside: avoid; }
h1 { margin: 0 0 3mm; font-size: 22pt; }
img { width: 45mm; height: 45mm; image-rendering: pixelated; }
.url { font: 11pt monospace; word-break: break-all; }
</style>
</head>
<body>
EOF
while IFS=$'\t' read -r id token; do
n=$((id - CT_ID_BASE))
url="https://$DOMAIN/t/$token/"
qr=state/qr/eq$n.png
qrencode -s 10 -m 2 -o "$qr" "$url"
cat <<EOF
<div class="slip">
<h1>Equipo $n</h1>
<img src="data:image/png;base64,$(base64 -w 0 "$qr")" alt="">
<p class="url">$url</p>
<p>Primer comando: <code>less LEEME</code></p>
</div>
EOF
done < <(sort -n "$TOKENS")
echo '</body>'
echo '</html>'
}
grep -qs '^template: 1' "/etc/pve/lxc/$TEMPLATE_ID.conf" ||
die "no existe la plantilla $TEMPLATE_ID: ejecuta antes ./template.sh"
command -v qrencode >/dev/null || die "falta qrencode: apt install qrencode"
mkdir -p state/qr
touch "$TOKENS"
for ((n = 1; n <= count; n++)); do
id=$((CT_ID_BASE + n))
conf=/etc/pve/lxc/$id.conf
if [[ ! -e $conf ]]; then
echo "eq$n: creando el CT $id"
create_team "$n"
continue
fi
echo "eq$n: el CT $id ya existe, se salta"
grep -q '^\[clean\]' "$conf" ||
echo " aviso: el CT $id no tiene snapshot 'clean', quedó a medias: pct destroy $id --purge y vuelve a ejecutar" >&2
[[ -n $(token_of "$id") ]] ||
echo " aviso: el CT $id no tiene token en $TOKENS, se queda sin ruta" >&2
done
write_routes > state/taller-routes.conf
pct push "$PROXY_ID" state/taller-routes.conf /etc/nginx/taller-routes.conf
pct exec "$PROXY_ID" -- nginx -tq
pct exec "$PROXY_ID" -- systemctl reload nginx
# Un CT recreado conserva su IP pero no su MAC: borra del proxy las entradas ARP obsoletas
pct exec "$PROXY_ID" -- ip neigh flush to "$SUBNET.0/24"
write_slips > state/papelitos.html
echo "rutas publicadas; imprime state/papelitos.html"

74
template.sh Executable file
View File

@@ -0,0 +1,74 @@
#!/usr/bin/env bash
# Se ejecuta en: host Proxmox.
# Uso: ./template.sh
# Construye la plantilla (TEMPLATE_ID) de la que se clonan los CT de equipo:
# paquetes, usuario alumno, servicio ttyd, los ficheros de files/ y los retos.
# Si la plantilla ya existe no hace nada; para rehacerla, antes pct destroy.
set -euo pipefail
cd "$(dirname "$0")"
# shellcheck source=SCRIPTDIR/common.sh
source ./common.sh
GEN_LOG=retos/1-logs/gen-access-log.sh
in_ct() {
pct exec "$TEMPLATE_ID" -- "$@"
}
conf=/etc/pve/lxc/$TEMPLATE_ID.conf
if [[ -e $conf ]]; then
grep -q '^template: 1' "$conf" ||
die "el CT $TEMPLATE_ID existe pero no es plantilla (¿quedó a medias?): pct destroy $TEMPLATE_ID"
echo "la plantilla $TEMPLATE_ID ya existe, no hay nada que hacer"
exit 0
fi
[[ -f $GEN_LOG ]] || die "no existe $GEN_LOG"
ttyd_bin=$(mktemp)
trap 'rm -f "$ttyd_bin"' EXIT
curl -fsSL -o "$ttyd_bin" "https://github.com/tsl0922/ttyd/releases/download/$TTYD_VERSION/ttyd.x86_64"
sha256sum --check --quiet <<< "$TTYD_SHA256 $ttyd_bin"
pveam update
os_image=$(pveam available --section system |
awk '$2 ~ /^debian-13-standard_.*_amd64\./ { print $2 }' | sort -V | tail -n 1)
[[ -n $os_image ]] || die "no hay imagen de Debian 13 en 'pveam available'"
# Sin grep -q: con pipefail, si grep sale antes de tiempo, pveam puede fallar por SIGPIPE
pveam list "$IMAGE_STORAGE" | grep -F "$os_image" >/dev/null ||
pveam download "$IMAGE_STORAGE" "$os_image"
# Sin privilegios; nesting es lo que recomienda Proxmox para systemd >= 254 en el CT
pct create "$TEMPLATE_ID" "$IMAGE_STORAGE:vztmpl/$os_image" \
--hostname taller-template \
--unprivileged 1 \
--features nesting=1 \
--rootfs "$CT_STORAGE:$CT_DISK_GB" \
--net0 "name=eth0,bridge=$EXT_BRIDGE,ip=dhcp"
pct start "$TEMPLATE_ID"
wait_for 60 in_ct getent hosts deb.debian.org >/dev/null ||
die "el CT $TEMPLATE_ID no tiene red"
in_ct apt-get update
in_ct env DEBIAN_FRONTEND=noninteractive apt-get install -y bash-completion shellcheck tmux \
vim nano less man-db gawk jq inotify-tools procps cron tree
in_ct apt-get clean
in_ct useradd --create-home --shell /bin/bash alumno
pct push "$TEMPLATE_ID" "$ttyd_bin" /usr/local/bin/ttyd --perms 755
pct push "$TEMPLATE_ID" files/ttyd.service /etc/systemd/system/ttyd.service
in_ct systemctl enable ttyd
pct push "$TEMPLATE_ID" files/LEEME /home/alumno/LEEME --user alumno --group alumno
# Readline ignora /etc/inputrc si existe ~/.inputrc; este lo incluye
pct push "$TEMPLATE_ID" files/inputrc /home/alumno/.inputrc --user alumno --group alumno
# El generador no entra en el CT: leyéndolo se sabría la respuesta
in_ct mkdir /home/alumno/retos
tar -C retos --exclude=gen-access-log.sh -cf - . | in_ct tar -C /home/alumno/retos -xf -
in_ct bash -c 'bash -s > /home/alumno/retos/1-logs/access.log' < "$GEN_LOG"
in_ct chown -R alumno:alumno /home/alumno/retos
pct shutdown "$TEMPLATE_ID"
pct set "$TEMPLATE_ID" --delete net0
pct template "$TEMPLATE_ID"
echo "plantilla $TEMPLATE_ID lista"