diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..e69de29 diff --git a/ilnostropianetaselvaggio.md b/ilnostropianetaselvaggio.md new file mode 100644 index 0000000..1a69c99 --- /dev/null +++ b/ilnostropianetaselvaggio.md @@ -0,0 +1,646 @@ +# Documentazione + +> Nota: tutte le configurazioni successive, e i relativi comandi, fanno riferimento a un OS Debian 12 + +## ssh + +ssh (Secure Shell) è un protocollo crittografico progettato per consentire la comunicazione sicura su una rete non sicura. Viene comunemente utilizzato per accedere in modo remoto a sistemi informatici e per eseguire comandi da remoto in modo sicuro. + +### Generazione delle chiavi + +Sulla propria macchina, generare le chiavi coi seguenti comandi: + +```bash +ssh-keygen -t ed25519 -f ~/.ssh/keyname + +cat ~/.ssh/keyname.pub +``` + +Quindi collegarsi al server remoto e caricare la chiave pubblica nel file `~/.ssh/authorized_keys`, situato nella home dell'utente autorizzato a connettersi, nel esempio *user1*. + +#### Configurazione ssh + +Sulla macchina remota, configurare ssh nel modo seguente + +```bash + > grep -v ^# /etc/ssh/sshd_config + +Include /etc/ssh/sshd_config.d/*.conf +Port 1329 +Protocol 2 +LogLevel INFO +MaxAuthTries 3 +PubkeyAuthentication yes +PasswordAuthentication no +PermitEmptyPasswords no +KbdInteractiveAuthentication no +UsePAM yes +PrintMotd no +Banner none +PermitRootLogin no +AllowUsers user1 +MACs hmac-sha1,hmac-sha2-256,hmac-sha2-512 +``` + +In particolare: + +- **Port 1329**: Specifica la porta su cui il server SSH ascolta le connessioni in arrivo. In questo caso, il server SSH ascolterà sulla porta 1329 anziché sulla porta predefinita 22. + +- **Protocol 2**: Specifica che il server SSH dovrebbe utilizzare solo la versione 2 del protocollo SSH. La versione 1 del protocollo è considerata meno sicura e non dovrebbe essere utilizzata. + +- **LogLevel INFO**: Imposta il livello di dettaglio dei log a "INFO", il che significa che verranno registrate informazioni di livello informativo nei log di sistema. + +- **MaxAuthTries 3**: Limita il numero di tentativi di autenticazione consentiti prima che una connessione venga interrotta. + +- **PubkeyAuthentication yes**: Abilita l'autenticazione tramite chiave pubblica. Gli utenti possono autenticarsi utilizzando una coppia di chiavi pubbliche e private anziché una password. + +- **PasswordAuthentication no**: Disabilita l'autenticazione tramite password. Gli utenti non possono accedere al server SSH inserendo una password. + +- **PermitEmptyPasswords no**: Impedisce agli utenti di utilizzare password vuote per l'autenticazione. + +- **KbdInteractiveAuthentication no**: Disabilita l'autenticazione interattiva basata sulla tastiera. + +- **UsePAM yes**: Abilita l'utilizzo del modulo di autenticazione PAM (Pluggable Authentication Modules) per gestire l'autenticazione degli utenti. + +- **PrintMotd no**: Impedisce la visualizzazione del "Message of the Day" all'accesso. + +- **Banner none**: Non visualizza alcun banner all'accesso. + +- **PermitRootLogin no**: Impedisce il login diretto come utente root. + +- **AllowUsers user1**: Specifica gli utenti che sono autorizzati a connettersi al server SSH. In questo caso, solo l'utente "user1" è autorizzato. + +Riavviare il servizio: + +```bash +systemctl restart ssh.service && systemctl restart sshd.service +``` + +Sulla propria macchina, creare il seguente file di configurazione: + +```bash +> cat .ssh/config +Host * + ForwardAgent yes + ControlMaster yes + Compression yes + +Host name + hostname ip_server + user user1 + IdentityFile ~/.ssh/keyname + TCPKeepAlive yes + port 1329 +``` + +Testare il collegamento. + +> Nota: per eliminare la schermata di benvenuto, dare il seguente comando, una volta che il collegamento sia avvenuto correttamente: `echo "" > /etc/motd` + +## fail2ban + +Fail2ban è un software open-source che monitora i log del sistema in tempo reale e, in base a determinati criteri di configurazione, blocca automaticamente gli indirizzi IP sospetti che tentano di accedere ripetutamente al server. Questo strumento aiuta a migliorare la sicurezza del server riducendo il rischio di accessi non autorizzati. + +Sulla macchina remota, installare fail2ban: + +```bash +apt install fail2ban +``` + +Verificare che nel file `/etc/fail2ban/jail.con` siano presenti le seguenti impostazioni: + +```bash +# "bantime" is the number of seconds that a host is banned. +bantime = 120m + +# A host is banned if it has generated "maxretry" during the last "findtime" +# seconds. +findtime = 5m + +# "maxretry" is the number of failures before a host get banned. +maxretry = 5 +``` + +### Configurazione fail2ban + +Creare il seguente file: + +```bash +> cat /etc/fail2ban/jail.d/defaults-debian.conf +[sshd] +enabled = true +port = 1329 +filter = sshd +maxretry = 3 +findtime = 5m +bantime = 120m +``` + +Questo file configura fail2ban per monitorare e proteggere il servizio ssh sulla porta 1329, consentendo un massimo di 3 tentativi di accesso non validi entro un periodo di 5 minuti prima di bloccare l'indirizzo IP sospetto per 120 minuti. + +Quindi abilitare e avviare il servizio: + +```bash +> systemctl enable --now fail2ban && systemctl status fail2ban.service +``` + +Infine, verificare che tutte le impostazioni siano corrette: + +```bash +> fail2ban-client status +Status +|- Number of jail: 1 +`- Jail list: sshd + + +> fail2ban-client status sshd +Status for the jail: sshd +|- Filter +| |- Currently failed: 0 +| |- Total failed: 0 +| `- File list: +`- Actions + |- Currently banned: 0 + |- Total banned: 0 + `- Banned IP list: +``` + +## ufw + +ufw (Uncomplicated Firewall) è un frontend per iptables che semplifica la gestione del firewall su sistemi Linux. + +Installare ufw col comando: + +```bash +apt install ufw && ufw enable +``` + +### Configurare ufw + +```bash +ufw default allow outgoing && ufw default deny incoming +``` + +Il precedente comando imposta le politiche predefinite del firewall per il traffico in uscita e in entrata. + +Questo comando configura UFW per consentire tutto il traffico in uscita e bloccare tutto il traffico in entrata di default, fornendo una base di sicurezza per il sistema. + +Infine, consentire solo il traffico in ingresso dalle porte tcp 80 e 443 e sulla porta 1329 per ssh: + +```bash +ufw allow 80/tcp && ufw allow 443/tcp && ufw allow 1329 +``` + +Verificare le impostazioni: + +```bash +> ufw status numbered +Status: active + + To Action From + -- ------ ---- +[ 1] 1329 ALLOW IN Anywhere +[ 2] 80/tcp ALLOW IN Anywhere +[ 3] 443/tcp ALLOW IN Anywhere +[ 4] 1329 (v6) ALLOW IN Anywhere (v6) +[ 5] 80/tcp (v6) ALLOW IN Anywhere (v6) +[ 6] 443/tcp (v6) ALLOW IN Anywhere (v6) +``` + +## caddy + +Un reverse proxy è un server che si trova tra i client e uno o più server di backend. Quando un client invia una richiesta al reverse proxy, questo instrada la richiesta al server di backend appropriato e restituisce la risposta al client. + +Caddy è un server web open-source che funge da reverse proxy e offre funzionalità avanzate come il rinnovo automatico dei certificati SSL, configurazione semplificata tramite file di configurazione Caddyfile e supporto per HTTP/2. + +### Installazione di caddy + +```bash +apt install caddy +``` + +### Configurazione + +Modificare il file seguente, in base ai servizi che si installeranno: + +```bash +> cat /etc/caddy/Caddyfile + +# Configurazione del server web + +https://www.mywebsite.it { + # Set this path to your site's directory. + root * /home/sistemostro/website/ + + # Enable the static file server. + file_server +} + +# Reindirizzamento dell traffico + +https://mywebsite.it { + redir https://www.mywebsite.it{uri} +} + +# Configurazione del reverse proxy + +# VAULTWARDEN + +https://vault.mywebsite.it { + reverse_proxy localhost:3001 +} + +# NTFY + +https://ntfy.mywebsite.it { + reverse_proxy localhost:3003 +} + +# RSS + +https://rss.mywebsite.it { + reverse_proxy localhost:3004 +} + +# COLLABORA + +https://code.mywebsite.it { + encode gzip + reverse_proxy localhost:3005 { + transport http { + tls_insecure_skip_verify + } + } +} + +# GITEA + +https://git.mywebsite.it { + reverse_proxy localhost:3006 +} + +# KUMA + +https://mon.mywebsite.it { + reverse_proxy localhost:3007 +} + +# CASTOPOD + +https://podcast.mywebsite.it { + reverse_proxy localhost:3008 +} + +# MOLLY + +https://molly.mywebsite.it { + reverse_proxy / localhost:8020 +} +``` + +Queste configurazioni consentono a Caddy di agire come reverse proxy per instradare il traffico verso i servizi specificati in base al sottodominio richiesto. + +Abilitare e avviare il servizio: + +```bash +> systemctl enable --now caddy.service +``` + +Verificare il log in tempo reale del servizio: + +```bash +> journalctl -f -u caddy.service +``` + +Quando Caddy riceve una richiesta su una determinata porta (ad esempio la porta 443 per HTTPS), gestirà internamente il routing del traffico verso i servizi backend specificati nel file di configurazione, senza dover aprire le porte sul firewall del sistema. Questo è uno dei vantaggi dell'utilizzo di un reverse proxy per gestire il traffico web in modo sicuro ed efficiente. + +> Nota: non tutte le precedenti operazioni vengono svolte in ordine, rispettivamente a come scritte. Bisogna inoltre possedere un dominio valido e configurare i record dns nel modo adeguato + +## Docker + +Docker è una piattaforma open-source che consente di creare, distribuire e gestire applicazioni in container. I container Docker consentono di isolare le applicazioni e le loro dipendenze in ambienti autonomi e possono essere eseguiti in modo consistente su qualsiasi sistema che abbia Docker installato. + +Docker Compose è uno strumento aggiuntivo che consente di definire e gestire applicazioni multi-container utilizzando un singolo file di configurazione, chiamato appunto `docker-compose.yml`. Docker Compose semplifica la gestione di applicazioni distribuite composte da più servizi, consentendo di avviare, arrestare e gestire l'intera applicazione con un singolo comando. + +Il file `.env` è un file di configurazione che contiene variabili d'ambiente utilizzate per configurare le applicazioni Docker. Queste variabili possono includere impostazioni come le porte di rete, le password, le chiavi di accesso e altre configurazioni specifiche dell'ambiente. + +Per installare docker e docker compose, seguire la guida ufficiale: [Install Docker Engine on Debian](https://docs.docker.com/engine/install/debian/) + +### Docker compose + +Questi i comandi principali, da dare nella cartella dove si trova il file `docker-compose.yml`: + +- `docker-compose pull`: Scarica le immagini dei servizi specificati nel file `docker-compose.yml`. +- `docker-compose up -d`: Avvia i container dei servizi definiti nel file `docker-compose.yml`. +- `docker-compose down`: Questo comando fermerà e rimuoverà i container, le reti e i volumi creati dall'esecuzione di `docker-compose up`. + +> Nota: tutte le variabili nei file docker-compose, sono gestite nei rispettivi file .env + +#### castopod + +```yml +> cat castopod/docker-compose.yml +services: + app: + image: castopod/castopod:latest + container_name: "castopod-app" + env_file: .env + volumes: + - castopod-media:/var/www/castopod/public/media + environment: + MYSQL_DATABASE: castopod + MYSQL_USER: castopod + MYSQL_PASSWORD: ${MYSQL_PASSWORD} + CP_BASEURL: ${CP_BASEURL} + CP_ANALYTICS_SALT: ${CP_ANALYTICS_SALT} + CP_CACHE_HANDLER: redis + CP_REDIS_HOST: redis + CP_REDIS_PASSWORD: ${CP_REDIS_PASSWORD} + CP_EMAIL_SMTP_HOST: ${CP_EMAIL_SMTP_HOST} + CP_EMAIL_FROM: ${CP_EMAIL_FROM} + CP_EMAIL_SMTP_USERNAME: ${CP_EMAIL_SMTP_USERNAME} + CP_EMAIL_SMTP_PASSWORD: ${CP_EMAIL_SMTP_PASSWORD} + CP_EMAIL_SMTP_PORT: 587 + networks: + - castopod-app + - castopod-db + ports: + - 3008:8000 + restart: unless-stopped + + mariadb: + image: mariadb:10.5 + container_name: "castopod-mariadb" + networks: + - castopod-db + volumes: + - castopod-db:/var/lib/mysql + environment: + MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD} + MYSQL_DATABASE: castopod + MYSQL_USER: castopod + MYSQL_PASSWORD: ${MYSQL_PASSWORD} + restart: unless-stopped + + redis: + image: redis:7.0-alpine + container_name: "castopod-redis" + command: --requirepass ${CP_REDIS_PASSWORD} + volumes: + - castopod-cache:/data + networks: + - castopod-app + +volumes: + castopod-media: + castopod-db: + castopod-cache: + +networks: + castopod-app: + castopod-db: +``` + +#### Collabora Editor + +```yml +> cat code/docker-compose.yml +services: + code: + container_name: code + image: collabora/code:latest + env_file: .env + restart: unless-stopped + environment: + password: ${COLLABORA_PASSWORD} + username: ${COLLABORA_USERNAME} + domain: ${COLLABORA_DOMAIN} + dictionaries: en it + extra_params: --o:ssl.enable=true --o:ssl.termination=false # Set SSL options + ports: + - 3005:9980 + volumes: + - /etc/localtime:/etc/localtime + - /etc/timezone:/etc/timezone + cap_add: + - MKNOD + tty: true +``` + +#### FreshRSS + +```yml +> cat freshrss/docker-compose.yml +services: + + freshrss: + image: freshrss/freshrss:latest + container_name: freshrss + hostname: freshrss + restart: unless-stopped + logging: + options: + max-size: 10m + volumes: + - data:/var/www/FreshRSS/data + - extensions:/var/www/FreshRSS/extensions + ports: + # If you want to open a port 8080 on the local machine: + - "3004:80" + environment: + TZ: Europe/Rome + CRON_MIN: '3,33' + +volumes: + data: + extensions: +``` + +#### gitea + +```bash +> cat gitea/docker-compose.yml +services: + gitea: + image: gitea/gitea:latest + env_file: .env + container_name: gitea + restart: unless-stopped + environment: + - USER_UID=102 + - USER_GID=109 + networks: + - gitea + volumes: + - ./gitea:/data + - /home/git/.ssh/:/data/git/.ssh + - /etc/timezone:/etc/timezone:ro + - /etc/localtime:/etc/localtime:ro + ports: + - "3006:3000" + - "2222:22" + +networks: + gitea: + external: false +``` + +##### ssh passthrough + +1) Creare sulla macchina remota l'utente di sistema git: + +```bash +> adduser --system --shell /bin/bash --gecos 'Git Version Control' --group --disabled-password --home /home/git git +``` + +2) Verificare GID e UID dell'utente, che andranno inseriti nel file docker-compose.yml: + +```bash +> getent passwd git +git:x:102:109:Git Version Control,,,:/home/git:/home/git/docker-shell +``` + +3) Nella home, creare il seguente script: + +```bash +> ll /home/git/ +Permissions Size User Date Modified Name +.rwxr--r-- 106 root 26 apr 18:32  docker-shell + + +> cat /home/git/docker-shell +#!/bin/sh +/usr/bin/docker exec -i -u git --env SSH_ORIGINAL_COMMAND="$SSH_ORIGINAL_COMMAND" gitea sh "$@" +``` + +4) Creare una chiave ssh per l'utente git e aggiungere la chiave pubblica al file `~/git/.ssh/authorized_keys`, che sara' montato direttamente nel container. + +```bash + sudo -u git ssh-keygen -t ed25519 -C git +sudo -u git cat /home/git/.ssh/git.pub | sudo -u git tee -a /home/git/.ssh/authorized_keys +sudo -u git chmod 600 /home/git/.ssh/authorized_keys +``` + +> Importante: +> La chiave pubblica dell'utente git deve essere aggiunta "così com'è", mentre tutte le altre chiavi pubbliche aggiunte tramite l'interfaccia web di Gitea saranno precedute da command="/usr [...]. + +5) Aggiungere l seguente blocco a `/etc/ssh/sshd_config` sull'host remoto: + +```bash +Match User git + AuthorizedKeysCommandUser git + AuthorizedKeysCommand /usr/bin/ssh -p 2222 -o StrictHostKeyChecking=no git@127.0.0.1 /usr/local/bin/gitea keys -c /data/gitea/conf/app.ini -e git -u %u -t %t -k %k +``` + +6) Riavviare il servizio ssh: `systemctl restart sshd`. + +7) Sulla propria macchina, inserire la seguente configurazione nel file `~/.ssh/config`: + +```bash +Host git.mywebsite.it + user username + IdentityFile ~/.ssh/private_key + TCPKeepAlive yes + port 2222 +``` + +#### uptime-kuma + +```yml +> cat kuma/docker-compose.yml +services: + uptime-kuma: + image: louislam/uptime-kuma:1 + container_name: uptime-kuma + volumes: + - ./uptime-kuma-data:/app/data + - /var/run/docker.sock:/var/run/docker.sock + ports: + - 3007:3001 + restart: always +``` + +#### ntfy + +```yml +> cat ntfy/docker-compose.yml +services: + ntfy: + image: binwiederhier/ntfy:latest + container_name: ntfy + command: + - serve + environment: + - TZ=CET # optional: set desired timezone + volumes: + - /var/cache/ntfy:/var/cache/ntfy + - /etc/ntfy:/etc/ntfy + ports: + - 3003:80 + restart: unless-stopped +``` + +#### Vaultwarden + +```yml +> cat vaultwarden/docker-compose.yml +services: + vaultwarden: + image: vaultwarden/server:latest + env_file: .env + container_name: vaultwarden + restart: unless-stopped + ports: + - 3001:80 # Needed for the ACME HTTP-01 challenge. + - 3002:443 + environment: + DOMAIN: ${VAULT_DOMAN} + LOG_FILE: "/data/vaultwarden.log" + LOG_LEVEL: "warn" + EXTENDED_LOGGING: "true" + SHOW_PASSWORD_HINT: "false" + SENDS_ALLOWED: "true" + LOGIN_RATELIMIT_MAX_BURST: 10 + LOGIN_RATELIMIT_SECONDS: 60 + ADMIN_RATELIMIT_MAX_BURST: 10 + ADMIN_RATELIMIT_SECONDS: 60 + ADMIN_TOKEN: ${VAULT_ADMIN_TOKEN} + EMERGENCY_ACCESS_ALLOWED: "true" + SIGNUPS_ALLOWED: "false" + SIGNUPS_VERIFY: true + SIGNUPS_VERIFY_RESEND_TIME: 3600 + SIGNUPS_VERIFY_RESEND_LIMIT: 5 + SMTP_HOST: ${VAULT_SMTP_HOST} + SMTP_FROM: ${VAULT_SMTP_FROM} + SMTP_SECURITY: "starttls" + SMTP_PORT: 587 + SMTP_USERNAME: ${VAULT_SMTP_USER} + SMTP_PASSWORD: ${VAULT_SMTP_PASSWD} + volumes: + - ./vw-data:/data +``` +## Collegamenti + +### ssh + +- [VPS e sicurezza - Marvin Pascale](https://blog.marvinpascale.it/posts/2022/vps-e-sicurezza/) +- [SSH server - Marvin Pascale](https://blog.marvinpascale.it/posts/2023/ssh-server/) +- [SSH config - Marvin Pascale](https://blog.marvinpascale.it/posts/2023/ssh-config/) +- [[Solved] sudo: unable to resolve host Error in Ubuntu Linux](https://linuxhandbook.com/sudo-unable-resolve-host/) +- [AI Chat](https://duckduckgo.com/?q=ciao&atb=v408-1&ia=chat) + +### fail2ban + +- [How to Secure Your Linux Computer with Fail2ban](https://www.howtogeek.com/675010/how-to-secure-your-linux-computer-with-fail2ban/) + +### docker compose + +- [Official Docker images | Castopod documentation](https://docs.castopod.org/getting-started/docker.html) +- [Installation - ntfy](https://docs.ntfy.sh/install/) +- [freshrss/freshrss - Docker Image | Docker Hub](https://hub.docker.com/r/freshrss/freshrss/#!) +- [CODE Docker image — SDK documentation](https://sdk.collaboraonline.com/docs/installation/CODE_Docker_image.html) +- [🔧 How to Install · louislam/uptime-kuma Wiki · GitHub](https://github.com/louislam/uptime-kuma/wiki/%F0%9F%94%A7-How-to-Install) +- [GitHub - vineethmn/vaultwarden-docker-compose: A self hosted password manager](https://github.com/vineethmn/vaultwarden-docker-compose) +- [Installation with Docker | Gitea Documentation](https://docs.gitea.com/next/installation/install-with-docker) +- [How to Install Gitea with Docker on Ubuntu {in 9 Steps}](https://phoenixnap.com/kb/gitea-docker) +- [Push to Create - Gitea Documentation](https://docs.gitea.com/next/usage/push-to-create)