# IT~gals - instalación de una raspberry pi para varios servicios Aquí os dejo el script que utilicé para la charla «Jugando con raspis», el 18/11/2020. ## instalación y configuración de raspios en una sd ``` export HOST='bona' export FQDN='bona.itgals.org' export USER='diego' export SD='/dev/mmcblk0' #COMPRUEBA QUE LA SD SE MONTA AQUÍ!!!! cd ~/descargas unalias ls if [ ! `ls *raspios*lite*img` ] ; then unzip *raspios*lite*zip fi IMG=`ls *raspios*lite*img` sudo umount /mnt/* sudo umount /media/diego/* sudo dd if=$IMG of=$SD bs=4M status=progress sudo mkdir -p /mnt/boot /mnt/rootfs sudo mount "${SD}p1" /mnt/boot/ sudo mount "${SD}p2" /mnt/rootfs/ sudo touch /mnt/boot/ssh cd /mnt/rootfs echo " tmpfs /tmp tmpfs defaults,noatime,mode=1777,size=50m 0 0 tmpfs /var/log tmpfs defaults,noatime,mode=1777,size=50m 0 0 tmpfs /var/tmp tmpfs defaults,noatime,mode=1777,size=50m 0 0 tmpfs /run tmpfs defaults,noatime,mode=1777,size=50m 0 0 " | sudo tee --append etc/fstab echo "127.0.0.1 $FQDN $HOST :1 localhost ip6-localhost ip6-loopback ff02::1 ip6-allnodes ff02::2 ip6-allrouters" | sudo tee etc/hosts echo "$HOST" | sudo tee etc/hostname echo " export EDITOR='vim' alias ls='ls --color -h' alias l='ls -l' alias ll='l -a' alias grep='grep --color' alias rgrep='rgrep --color' alias df='df -h' alias du='du -h' alias vi=vim alias uf='sudo apt update && sudo apt full-upgrade -y && sudo apt autoremove -y && sudo apt clean'" | sudo tee --append home/pi/.bashrc echo "clear" | sudo tee --append home/pi/.bash_logout sudo sed -i "s/pi:/$USER:/g" etc/passwd sudo sed -i "s/:pi$/:$USER/g" etc/group sudo sed -i "s/^pi:/$USER:/g" etc/group sudo sed -i "s/^pi:/$USER:/g" etc/shadow sudo mv home/pi home/$USER sudo sed -i 's|^%sudo\tALL=(ALL:ALL) ALL|%sudo\tALL=(ALL) NOPASSWD:ALL|g' etc/sudoers cd ~/escritorio sudo umount /mnt/boot sudo umount /mnt/rootfs sudo rmdir /mnt/boot /mnt/rootfs ``` ## securización sin pretensiones Lo primero es crear un juego de llaves SSH en nuestro ordenador, porque un poco más adelante necesitaremos la parte pública de la misma. ``` ssh-keygen -t rsa -b 4096 -f ~/$USER@$FQDN.key ``` Ahora iniciamos la raspi con normalidad (y un cable de red) y nos conectamos a ella por SSH: > `ssh -l $USER $HOST` contraseña raspberry ``` export HOST='bona' export FQDN='bona.itgals.org' export USER='diego' sudo passwd $USER sudo rfkill unblock `rfkill | grep wlan | awk '{print $1}'` sudo sed -i '/^#/d' /etc/apt/sources.list sudo sed -i '/^$/d' /etc/apt/sources.list sudo sed -i '/deb-src/d' /etc/apt/sources.list #sudo sed -i 's/$/contrib non-free/' /etc/apt/sources.list sudo sed -i '/^#/d' /etc/apt/sources.list.d/raspi.list sudo sed -i '/^$/d' /etc/apt/sources.list.d/raspi.list sudo sed -i '/deb-src/d' /etc/apt/sources.list.d/raspi.list sudo apt purge -y alsa-utils triggerhappy wpasupplicant pi-bluetooth bluez bluez-firmware cpp* dmidecode g++* gcc-[4567]* gdb* geoip-database build-essential tcc* dpkg-dev luajit libluajit-5.1-common nano ncdu patch plymouth libplymouth4 tasksel tasksel-data traceroute rpcbind samba-common v4l-utils xdg-user-dirs cifs-utils dbus libdbus-* sudo apt purge -y `dpkg -l | grep ^rc | awk '{print $2}'` sudo apt autoremove -y sudo apt update sudo apt full-upgrade -y sudo apt install -y bash-completion vim ntp htop sudo apt autoremove -y sudo apt clean mkdir -p ~/.ssh echo "PON AQUÍ LA PARTE PÚBLICA DE TU LLAVE SSH" | tee -a ~/.ssh/authorized_keys [ `dpkg -l openssh-server | grep ^ii | wc -l` != '1' ] && \ sudo apt-get install -y openssh-server openssh-client SSHD_CFG="/etc/ssh/sshd_config" sudo sed -i 's|#Port 22|Port 22|' $SSHD_CFG sudo sed -i 's|#HostKey|HostKey|' $SSHD_CFG sudo sed -i 's|#SyslogFacility|SyslogFacility|' $SSHD_CFG sudo sed -i 's|#LogLevel|LogLevel|' $SSHD_CFG sudo sed -i 's|#LoginGraceTime|LoginGraceTime|' $SSHD_CFG sudo sed -i 's|#PermitRootLogin prohibit-password|PermitRootLogin no|' $SSHD_CFG sudo sed -i 's|#StrictModes|StrictModes|' $SSHD_CFG sudo sed -i 's|#MaxAuthTries 6|MaxAuthTries 2|' $SSHD_CFG sudo sed -i 's|#MaxSessions 10|MaxSessions 3|' $SSHD_CFG sudo sed -i 's|#PubkeyAuthentication|PubkeyAuthentication|' $SSHD_CFG sudo sed -i 's|#AuthorizedKeysFile|AuthorizedKeysFile|' $SSHD_CFG sudo sed -i 's|#AuthorizedKeysCommand|AuthorizedKeysCommand|' $SSHD_CFG sudo sed -i 's|#IgnoreRhosts|IgnoreRhosts|' $SSHD_CFG sudo sed -i 's|#PasswordAuthentication yes|PasswordAuthentication no|' $SSHD_CFG sudo sed -i 's|#PermitEmptyPasswords|PermitEmptyPasswords|' $SSHD_CFG sudo sed -i 's|#AllowAgentForwarding yes|AllowAgentForwarding no|' $SSHD_CFG sudo sed -i 's|#AllowTcpForwarding yes|AllowTcpForwarding no|' $SSHD_CFG sudo sed -i 's|X11Forwarding yes|X11Forwarding no|' $SSHD_CFG sudo sed -i 's|#MaxStartups 10:30:100|MaxStartups 2|' $SSHD_CFG sudo sed -i 's|#Banner none|Banner none|' $SSHD_CFG echo "#-- DebianBanner no AllowUsers $USER " | sudo tee -a $SSHD_CFG sudo /etc/init.d/ssh restart ``` Lo probamos en otro terminal: ``` export HOST='bona' export FQDN='bona.itgals.org' export USER='diego' ssh -i ~/$USER@$FQDN.key -l $USER bona ``` ### Instalación del núcleo de 64 bits y arranque (sólo raspis 4b 64 bits) ¿Núcleo Linux 64 bits? ¡Por supuesto! El resultado que es que pasará de este núcleo a este otro: ``` $ uname -a Linux bona 5.4.51-v7l+ #1333 SMP Mon Aug 10 16:51:40 BST 2020 armv7l GNU/Linux $ uname -a Linux bona 5.4.51-v8+ #1327 SMP PREEMPT Thu Jul 23 11:11:34 BST 2020 aarch64 GNU/Linux ``` ``` sudo rpi-update echo -e "\n# 64 bits\narm_64bit=1" | sudo tee -a /boot/config.txt sudo reboot && exit ``` La raspi se reinicia. ## DDNS Voy a añadir los dominios al fichero `/etc/hosts` de mi ordenador para simular que las peticiones se hacen desde internet: ``` echo ' # raspis en itgals 192.168.40.2 diegomc.ddnsgeek.com 192.168.40.2 diegoblog.ddnsgeek.com' | sudo tee -a /etc/hosts ``` ## Instalación de apache Primero instalaremos apache para dar soporte a una web estática con el currículum. La plantilla del curriculum online la he bajado de http://www.thomashardy.me.uk/free-responsive-html-css3-cv-template. `ssh -i ~/$USER@$FQDN.key -l $USER bona` ``` sudo apt update sudo apt install -y apache2 ``` Ahora descargamos, configuramos e instalamos la web estática. Para que `apache` la utilice tenemos que crear un fichero de configuración donde se define el `VirtualHost`. ``` cd wget http://www.thomashardy.me.uk/demos/cv-template.zip unzip cv-template.zip && rm -f cv-template.zip mv CV-Template diegomc.ddnsgeek.com sed -i 's|Joe Bloggs|Diego Mart\ínez Casta\ñeda|g' diegomc.ddnsgeek.com/index.html sed -i "s|joe@bloggs.com|diego@diegomc.ddnsgeek.com|g" diegomc.ddnsgeek.com/index.html sed -i "s|www.bloggs.com|diegomc.ddnsgeek.com|g" diegomc.ddnsgeek.com/index.html find diegomc.ddnsgeek.com -type d -exec chmod 755 {} \; find diegomc.ddnsgeek.com -type f -exec chmod 644 {} \; sudo chown -R www-data:www-data diegomc.ddnsgeek.com sudo mv diegomc.ddnsgeek.com /var/www/diegomc.ddnsgeek.com echo ' ServerName diegomc.ddnsgeek.com ServerAlias www.diegomc.ddnsgeek.com ServerAdmin webmaster@diegomc.ddnsgeek.com DocumentRoot /var/www/diegomc.ddnsgeek.com ErrorLog ${APACHE_LOG_DIR}/diegomc.ddnsgeek.com-error.log CustomLog ${APACHE_LOG_DIR}/diegomc.ddnsgeek.com-access.log combined ' | sudo tee /etc/apache2/sites-available/diegomc.ddnsgeek.com.conf sudo a2dissite 000-default.conf sudo a2ensite diegomc.ddnsgeek.com.conf sudo systemctl reload apache2 ``` Lo probamos en un navegador: diegomc.ddnsgeek.com ## Instalación de MariaDB ``` sudo apt install -y mariadb-server mariadb-client # en lugar de mysql_secure_installation db_root_password="SuperSecurePassword" sudo mysql --user=root <<_EOF_ UPDATE mysql.user SET Password=PASSWORD('${db_root_password}') WHERE User='root'; DELETE FROM mysql.user WHERE User=''; DELETE FROM mysql.user WHERE User='root' AND Host NOT IN ('localhost', '127.0.0.1', '::1'); DROP DATABASE IF EXISTS test; DELETE FROM mysql.db WHERE Db='test' OR Db='test\\_%'; FLUSH PRIVILEGES; _EOF_ ``` ## Instalación de php7 ``` sudo apt install -y php7.3 php7.3-mysql php7.3-gd sudo a2enmod rewrite sudo /etc/init.d/apache2 restart ``` ## Instalación de WordPress En mariaDB, En mariaDB, creamos una base de datos y un usuario con permisos en ella: ``` sudo mariadb -u root -e "CREATE DATABASE diegoblog_ddnsgeek_com ; GRANT ALL ON diegoblog_ddnsgeek_com.* TO 'diegoblog_ddnsgeek_com'@'localhost' IDENTIFIED BY 'SuperSecure2';" ``` ``` cd wget https://es.wordpress.org/latest-es_ES.tar.gz sudo tar xvfz latest-es_ES.tar.gz && rm -f latest-es_ES.tar.gz mv wordpress diegoblog.ddnsgeek.com sudo find diegoblog.ddnsgeek.com -type d -exec chmod 755 {} \; sudo find diegoblog.ddnsgeek.com -type f -exec chmod 644 {} \; sudo chown www-data:www-data diegoblog.ddnsgeek.com sudo mv diegoblog.ddnsgeek.com ~www-data/diegoblog.ddnsgeek.com echo ' ServerName diegoblog.ddnsgeek.com ServerAdmin webmaster@diegoblog.ddnsgeek.com DocumentRoot /var/www/diegoblog.ddnsgeek.com DirectoryIndex index.html index.php ErrorLog ${APACHE_LOG_DIR}/diegoblog.ddnsgeek.com_error.log TransferLog ${APACHE_LOG_DIR}/diegoblog.ddnsgeek.com_access.log #SSLEngine on #SSLCertificateFile /etc/letsencrypt/live/diegoblog.ddnsgeek.com/fullchain.pem #SSLCertificateKeyFile /etc/letsencrypt/live/diegoblog.ddnsgeek.com/privkey.pem #SSLProtocol TLSv1 TLSv1.1 TLSv1.2 -SSLv2 -SSLv3 #SSLHonorCipherOrder On #SSLCipherSuite AES256+EECDH:AES256+EDH Options FollowSymLinks Order allow,deny Allow from all AllowOverride All RewriteCond %{HTTP_HOST} !^www\. [NC] RewriteRule ^ %{REQUEST_SCHEME}://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L] ' | sudo tee /etc/apache2/sites-available/diegoblog.ddnsgeek.com.conf sudo a2enmod rewrite sudo a2ensite diegoblog.ddnsgeek.com.conf sudo systemctl restart apache2 ``` Lo probamos en el navegador: diegoblog.ddnsgeek.com ## Instalación y uso de certbot (certificado TLS con letsencrypt) Instalamos certbot: ``` sudo apt install -y certbot python-certbot-apache sudo certbot certonly --apache --email no@email.org --agree-tos -d diegomc.ddnsgeek.com sudo certbot certonly --apache --email no@email.org --agree-tos -d diegoblog.ddnsgeek.com ``` Y adaptamos apache para que utilice el certificado: ``` sudo sed -i 's|VirtualHost *:80|VirtualHost *:443|' /etc/apache2/sites-available/*ddnsgeek.com.conf sudo sed -i 's|#SSL|SSL|' /etc/apache2/sites-available/*ddnsgeek.com.conf sudo a2enmod ssl sudo systemctl restart apache2 ``` ## DDNS con ddclient ``` sudo apt install -y ddclient # salir del menú respondiendo cosas aleatorias echo "daemon=60 # Check every 60 seconds. syslog=yes # Log update msgs to syslog. mail=root # Mail all msgs to root. mail-failure=root # Mail failed update msgs to root. pid=/var/run/ddclient.pid # Record PID in file. use=web, web=checkip.dynu.com/, web-skip='IP Address' # Get ip from server. server=api.dynu.com # IP update server. protocol=dyndns2 login=superroot # Your username. password=SuperSícretPasgüor # Password or MD5/SHA256 of password. diegomc.ddnsgeek.com # List one or more hostnames one on each line. diegoblog.ddnsgeek.com" | sudo tee /etc/ddclient.conf sudo /etc/init.d/ddclient restart ``` ## último paso Borramos todos los paquetes que hemos instalado para liberar espacio. ``` sudo apt auto-remove -y sudo apt clean ```