23 de febrero de 2025

Protocol for Setting Up OpenVPN on Raspberry Pi Using PiVPN

This guide will walk you through installing and configuring OpenVPN on a Raspberry Pi using PiVPN.


1. Prerequisites

  • Raspberry Pi (Raspberry Pi 3, 4, or 5 recommended)
  • Raspberry Pi OS (Lite or Full version)
  • Internet connection
  • SSH access or direct terminal access
  • Static IP or Dynamic DNS (DDNS) for external access

2. Update and Upgrade System

Before installing OpenVPN, update the system:

sudo apt update && sudo apt upgrade -y

3. Install PiVPN

Run the PiVPN installation script:

curl -L https://install.pivpn.io | bash

This launches an interactive installer.


4. Configure OpenVPN

During installation, follow these steps:

  1. Select OpenVPN when prompted.

  2. Set Static IP Address
    • The installer will ask if you want to set a static IP.
    • Accept the default or manually configure one.

  3. Select UDP or TCP
    • UDP (default, recommended) for better performance.
    • TCP for firewall bypassing but slower speed.

  4. Choose Port (Default: 1194)
    • You can change it if needed.

  5. Choose Encryption Settings
    • Select RSA key size (default: 2048-bit or 4096-bit for stronger security).

  6. Select DNS Provider
    • Choose from OpenDNS, Google, Cloudflare, or a custom DNS.

  7. Confirm Installation
    • The script will install and configure OpenVPN.

5. Create a VPN User Profile

After installation, create a VPN user profile:

pivpn add

Follow the prompts to:

  • Enter a username.
  • Set a password (if required).

This will generate a .ovpn configuration file stored in /home/pi/configs/.


6. Configure Port Forwarding

To access the VPN from outside your network:

  1. Log in to your router’s admin panel.
  2. Locate Port Forwarding settings.
  3. Forward UDP Port 1194 to your Raspberry Pi’s local IP address.
  4. Save and restart your router.

7. Transfer the VPN Configuration File

To connect to your VPN, transfer the .ovpn file to your client device:

  • Use SCP, SFTP, or a USB drive to move the file.
  • Example command for SCP:
    scp pi@your_rpi_ip:/home/pi/configs/client.ovpn ~/Downloads/
    
  • Alternatively, use an SFTP client like WinSCP or FileZilla.

8. Connect to OpenVPN

  • PC (Windows/macOS/Linux):

    1. Install the OpenVPN client from openvpn.net.
    2. Import the .ovpn file.
    3. Click Connect.
  • Android/iOS:

    1. Install OpenVPN Connect from the App Store or Google Play.
    2. Import the .ovpn file.
    3. Connect to your VPN.

9. (Optional) Set Up Dynamic DNS (DDNS)

If your public IP changes frequently, use DDNS:

  • Sign up for a free No-IP or DuckDNS account.
  • Configure DDNS on your router or install a DDNS client on the Raspberry Pi.

Example (for No-IP):

sudo apt install ddclient
sudo nano /etc/ddclient.conf

Add your No-IP credentials and domain.


10. Test the VPN

  • Connect from an external network (e.g., mobile data).
  • Visit whatismyipaddress.com to check if your public IP matches your VPN server.

That's it! 馃帀 Your OpenVPN server on Raspberry Pi is now set up.

Let me know if you need further assistance! 馃殌

 

References:

ChatGPT. (2025, February 23). How to set up OpenVPN with a dynamic IP using DDNS on Raspberry Pi. OpenAI. Retrieved from https://chat.openai.com

ChatGPT. (2025, February 23). A conceptual digital illustration representing VPN, Linux, Raspberry Pi OS, Raspberry Pi, and travel [AI-generated image]. OpenAI.

 

4 de septiembre de 2024

Configurar HTTPS en apache2 con certificado autofirmado

Configurar Apache2 para usar HTTPS con un certificado autofirmado es un proceso relativamente sencillo. A continuaci贸n te guiar茅 paso a paso en c贸mo hacerlo en un sistema Linux, como Ubuntu o Debian.

### Paso 1: Instalar Apache2
Si no tienes Apache2 instalado, puedes hacerlo ejecutando el siguiente comando:

```bash
sudo apt update
sudo apt install apache2
```

### Paso 2: Habilitar el m贸dulo SSL de Apache
Apache tiene un m贸dulo para manejar conexiones SSL llamado `mod_ssl`. Para habilitarlo, ejecuta:

```bash
sudo a2enmod ssl
```

### Paso 3: Crear un certificado SSL autofirmado
Ahora vamos a crear un certificado autofirmado y una clave privada. Por defecto, el certificado SSL se genera para 365 d铆as. Si deseas un per铆odo diferente, puedes cambiar el valor despu茅s de `-days`.

```bash
sudo mkdir /etc/apache2/ssl
sudo openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout /etc/apache2/ssl/apache-selfsigned.key -out /etc/apache2/ssl/apache-selfsigned.crt
```

Este comando har谩 lo siguiente:
- `-x509`: Indica que vamos a crear un certificado autofirmado.
- `-nodes`: No ciframos el archivo de clave privada.
- `-days 365`: El certificado ser谩 v谩lido por 365 d铆as.
- `-newkey rsa:2048`: Generamos una clave RSA de 2048 bits.
- `-keyout`: El archivo donde se almacenar谩 la clave privada.
- `-out`: El archivo donde se almacenar谩 el certificado.

Durante la generaci贸n del certificado, te pedir谩 informaci贸n como el nombre del pa铆s, ciudad, organizaci贸n, etc. Puedes completar estos campos o dejarlos en blanco.

### Paso 4: Configurar Apache para usar SSL
Ahora necesitamos configurar Apache para utilizar el certificado autofirmado. Vamos a modificar el archivo de configuraci贸n SSL predeterminado.

1. Abre el archivo de configuraci贸n de SSL para editarlo:

   ```bash
   sudo nano /etc/apache2/sites-available/default-ssl.conf
   ```

2. Busca las siguientes l铆neas y aseg煤rate de que apunten a los archivos de certificado y clave privada que acabas de crear:

   ```bash
   SSLCertificateFile /etc/apache2/ssl/apache-selfsigned.crt
   SSLCertificateKeyFile /etc/apache2/ssl/apache-selfsigned.key
   ```

3. Si deseas, puedes modificar otras configuraciones en este archivo para adaptarlas a tus necesidades, como el nombre del servidor (`ServerName`).

### Paso 5: Habilitar el sitio SSL
Con el archivo configurado, habilitamos el sitio SSL predeterminado con el siguiente comando:

```bash
sudo a2ensite default-ssl.conf
```

### Paso 6: Reiniciar Apache
Para aplicar los cambios, reinicia Apache:

```bash
sudo systemctl restart apache2
```

### Paso 7: Prueba la configuraci贸n
Ahora deber铆as poder acceder a tu servidor Apache a trav茅s de HTTPS. Abre un navegador y visita `https://<tu-dominio>` o `https://<tu-direcci贸n-ip>`. Dado que est谩s utilizando un certificado autofirmado, el navegador mostrar谩 una advertencia de seguridad. Puedes omitir esta advertencia para continuar.

### Opcional: Redirigir HTTP a HTTPS
Si deseas redirigir todo el tr谩fico HTTP a HTTPS, puedes a帽adir una redirecci贸n en el archivo de configuraci贸n de tu sitio principal. Abre el archivo de configuraci贸n de tu sitio en `/etc/apache2/sites-available/000-default.conf` y a帽ade lo siguiente dentro del bloque `<VirtualHost *:80>`:

```apache
<VirtualHost *:80>
    ServerName tu-dominio.com
    Redirect / https://tu-dominio.com/
</VirtualHost>
```

Luego, reinicia Apache nuevamente:

```bash
sudo systemctl restart apache2
```

### Conclusi贸n

Ahora has configurado Apache2 para usar HTTPS con un certificado SSL autofirmado. Aunque este tipo de certificados son 煤tiles para pruebas y entornos de desarrollo, para producci贸n es recomendable usar un certificado emitido por una Autoridad de Certificaci贸n (CA), como los proporcionados por Let's Encrypt.

Ref:

data from GPT-4 of OpenAI.
(I) Prompt: Como configurar apache2 con https usando certificado autofrmado.
(II) Image prompt: An illustration showing the process of configuring HTTPS on an Apache2 server using a self-signed certificate. The image should depict a server terminal with Apache2 logo, SSL keys being generated, and a certificate being configured. Include visual elements like a shield icon representing security (HTTPS), command-line code snippets, and a simplified server diagram with arrows indicating data flow over HTTPS. The overall tone should be technical yet approachable, with clear, organized elements representing each step in the setup process.

Image by Google Gemini 2025.

20 de mayo de 2023

Solventar Error de Firmas con aptitude update

Cuando aparace un error de verificaci贸n de firmas p煤blicas al actualizar los paquetes linux-mint con aptitude, como el ejemplo:

#aptitude update
...
...
Err https://repo.protonvpn.com/debian unstable InRelease      
  Las firmas siguientes no se pudieron verificar porque su clave p煤blica no est谩 disponible: NO_PUBKEY YourKeyHere
...

Soluci贸n:

#apt-key adv --keyserver keyserver.ubuntu.com --recv-keys YourKeyHere

Executing: /tmp/apt-key-gpghome.czzxh7ycXx/gpg.1.sh --keyserver keyserver.ubuntu.com --recv-keys YourKeyHere
gpg: clave YourKeyHere: clave p煤blica "Proton Technologies AG <opensource@proton.me>" importada
gpg: Cantidad total procesada: 1
gpg:               importadas: 1 

Ref:
https://chat.openai.com
http://misnotaslinux.blogspot.com/2011/03/error-de-gpg-nopubkey.html

 

21 de marzo de 2023

Montar una imagen de tarjeta SD de rpi en linux

1) Descomprimir el fichero SDrpi.img.gz manteniendo el original:

# gzip -dk SDrpi.img.gz

 

2) ver estructura del fichero imagen:

# fdisk -l SDrpi.img

Unidades: sectores de 1 * 512 = 512 bytes
Tama帽o de sector (l贸gico/f铆sico): 512 bytes / 512 bytes
Tama帽o de E/S (m铆nimo/贸ptimo): 512 bytes / 512 bytes
Tipo de etiqueta de disco: dos
Identificador del disco: 0xb111a06d

Dispositivo Inicio Comienzo  Final Sectores Tama帽o Id Tipo

SDrpi.img1            8192    93814    85623  41,8M  c W95 FAT32 (LBA)
SDrpi.img2           94208 62333951 62239744  29,7G 83 Linux 

 

3) Montar la partici贸n 2 en /mnt/tmp:

Calcular valor del offset:

# echo "512 * 94208" | bc
48234496

# mount -o loop,offset=48234496 SDrpi.img /mnt/tmp

 

4) Comprobar:

$ cd /mnt/tmp

$ ll
total 104K
drwxr-xr-x   2 root root 4,0K sep 11  2019 bin
drwxr-xr-x   2 root root 4,0K sep  7  2017 boot
drwxr-xr-x   4 root root 4,0K sep  7  2017 dev
drwxr-xr-x 123 root root  12K nov  6  2019 etc
drwxr-xr-x   4 root root 4,0K ene  8  2019 home
drwxr-xr-x  16 root root 4,0K feb 20  2019 lib
drwx------   2 root root  16K sep  7  2017 lost+found
drwxr-xr-x   4 root root 4,0K sep 26  2017 media
drwxr-xr-x   3 root root 4,0K oct 24  2017 mnt
drwxr-xr-x   5 root root 4,0K feb  3  2019 opt
drwxr-xr-x   2 root root 4,0K jul 28  2017 proc
drwx------  24 root root 4,0K nov 22  2019 root
drwxr-xr-x   6 root root 4,0K sep  7  2017 run
drwxr-xr-x   2 root root  12K oct  2  2019 sbin
drwxr-xr-x   2 root root 4,0K sep  7  2017 srv
drwxr-xr-x   2 root root 4,0K jul 28  2017 sys
drwxrwxrwt   8 root root 4,0K nov 22  2019 tmp
drwxr-xr-x  11 root root 4,0K sep  7  2017 usr
drwxr-xr-x  12 root root 4,0K oct 14  2017 var

Ok, ya tenemos accesible el sistema de archivos de la images de la tarjeta SD de raspberry pi, disponible para consultar o tomar los que necesitemos.

 

5) desmontar al terminar:

# sudo umount /mnt/tmp




8 de marzo de 2023

Rpi test SD card speed with hdparm

 $ hdparm -tT /dev/mmcblk0 

------------------------------------------------------------ 

@rpi4:~ $ sudo hdparm -tT /dev/sdd  (16GB class 4 SD by USB reader)
/dev/sdd:
 Timing cached reads:   1404 MB in  2.00 seconds = 702.06 MB/sec
 Timing buffered disk reads:  58 MB in  3.05 seconds =  19.03 MB/sec

------------------------------------------------------------ 

@rpi4:~ $ sudo hdparm -tT /dev/mmcblk0 (128GB SD, class 10)
/dev/mmcblk0:
 Timing cached reads:   1470 MB in  2.00 seconds = 735.12 MB/sec
 Timing buffered disk reads: 128 MB in  3.02 seconds =  42.42 MB/sec

------------------------------------------------------------ 

@rpiap:~ $ sudo hdparm -tT /dev/mmcblk0 (16GB SD Class 10)
/dev/mmcblk0:
 Timing cached reads:   874 MB in  2.00 seconds = 437.44 MB/sec
 Timing buffered disk reads:  66 MB in  3.02 seconds =  21.86 MB/sec

------------------------------------------------------------

@rpi:~ $ sudo hdparm -tT /dev/mmcblk0 (32 GB SD class 10)
/dev/mmcblk0:
 Timing cached reads:   410 MB in  2.01 seconds = 204.42 MB/sec
 Timing buffered disk reads:  66 MB in  3.04 seconds =  21.70 MB/sec

------------------------------------------------------------ 

2 de marzo de 2023

Acivate event_scheduler in mariaDB

Protocol:


1) Edit mariadb config file:


# nano /etc/mysql/mariadb.conf.d/50-server.cnf

include the line: "event_sheduler = on"

2) Restart mariadb service:


# service mariadb restart

3) Check if allright:

$ service mariadb status 

 

Confirm that events are executed from now.

28 de febrero de 2023

How to Compile and Upload .ino file to Arduino board in Rpi Linux Shell


I have a system composed by RpiB+ and Arduino Uno board working together, monitoring parameters, triggering reles, storing data into MariaDB and presenting with apache2 webserver.

When I have to change arduino program I have to open vnc session, execute arduino-ide, edit sketch, compile and upload to arduino board !!, ... painful due limited resources o my old RpiB+.

Thus, can I compile and upload and .ino file from rpi linux shell ??

Yes, and very ease.

 

Protocol:

Install arduino, if not installed already:

# aptitude install arduino

Compile and upload Shell command:

$ arduino --upload yourfile.ino --port yourArduinoport

 

Example:

$ arduino --upload example.ino --port /dev/ttyACM0

Picked up JAVA_TOOL_OPTIONS:
Cargando configuraci贸n...
Inicializando paquetes...
Preparando tarjetas...
Verficando...
...
El Sketch usa 16464 bytes (51%) del espacio de almacenamiento de programa. El m谩ximo es 32256 bytes.
Las variables Globales usan 754 bytes (36%) de la memoria din谩mica, dejando 1294 bytes para las variables locales. El m谩ximo es 2048 bytes.
Subiendo...
...

I can also modify the .ino sketches with nano, compile and upload them to arduino from shell, without need any graphical environment.

Ref.:
https://arduino.stackexchange.com/questions/15893/how-to-compile-upload-and-monitor-via-the-linux-command-line

27 de febrero de 2023

Overlay Rpi Firmware: disable Wifi, Bluetooth and easy Shutdown Button

Rpi's Firmware has many posibilities to configure changing /boot/config.txt file


Usefull overlays:

Disable bluetooth:

Name: disable-bt
Info: Disable onboard Bluetooth on Pi 3B, 3B+, 3A+, 4B and Zero W, restoring
UART0/ttyAMA0 over GPIOs 14 & 15.
N.B. To disable the systemd service that initialises the modem so it
doesn't use the UART, use 'sudo systemctl disable hciuart'.
Load: dtoverlay=disable-bt
Params: <None>

Disable wifi:

Name: disable-wifi
Info: Disable onboard WLAN on Pi 3B, 3B+, 3A+, 4B and Zero W.
Load: dtoverlay=disable-wifi
Params: <None>


Safe shutdown button:

Clinton

Hey Shane,
No this won’t but if you wire the button to GPIO3 and add
dtoverlay=gpio-shutdown
to /boot/config.txt it will give you a safe shutdown and start up again.

You can find out more about it in the overlay readme search for shutdown and you will find it.
@Josh Told me about this just after I finished writing the tutorial.

-----------------------------------------------------------

Tested in my Rpi4: NOT WORK !!!

other recipe:

Tentsing this:

Include in /boot/config.txt and reboot

dtoverlay=gpio-shutdown,gpio_pin=3

NOT WORK !!

seems that nt work with GPIO_3 = SCL

Changing to GPI #17

===================================================

Include into /boot/config.txt and reboot

dtoverlay=gpio-shutdown,gpio_pin=17

YES, it's WORKS, can shutdown rpi4 with switch from GPIO#17 -- GND

===================================================


Ref:

https://github.com/raspberrypi/firmware/blob/master/boot/overlays/README

26 de febrero de 2023

Linux shell Upgrade from RpiOS-10 buster to RpiOS-11 bullseye, fast recipe.

Protocol:

 0 - Make rpi SD backup in other linux computer:
# dd if=/dev/mmcblk0 status=progress bs=5M | gzip -9 > rpi-sd-bck-$(date +%Y%m%d_%H%M%S).img.gz
 

1 - Check current version: 
$ lsb_release -a
 
No LSB modules are available.
Distributor ID: Raspbian
Description:    Raspbian GNU/Linux 10 (buster)
Release:        10
Codename:       buster

 
2- Update, Upgrade current version
# aptitude update
# aptitude upgrade -y
# aptitude dist-upgrade -y
 
3 - Update Rpi firmware (?)
# rpi-update
 
4 - Change sourceslist.list file: "buster" to "bullseye"
# nano /etc/apt/sources.list
 
old: 
deb http://raspbian.raspberrypi.org/raspbian/ buster main contrib non-free rpi
new:
deb http://raspbian.raspberrypi.org/raspbian/ bullseye main contrib non-free rpi

5 - Update & Upgrade new OS version
# aptitude update
# aptitude upgrade -y

6 - Clean installation files
# aptitude autoclean
 
7 - Reboot the system
# reboot
 
8 - Check OS
$ lsb_release -a
 or
$ neofetch
  `.::///+:/-.        --///+//-:``    pi@rpi4 
`+oooooooooooo:   `+oooooooooooo:    -------  
 /oooo++//ooooo:  ooooo+//+ooooo.    OS: Raspbian GNU/Linux 11 (bullseye) armv7l  
 `+ooooooo:-:oo-  +o+::/ooooooo:     Host: Raspberry Pi 4 Model B Rev 1.4  
  `:oooooooo+``    `.oooooooo+-      Kernel: 5.10.103-v7l+  
    `:++ooo/.        :+ooo+/.`       Uptime: 13787B year 
       ...`  `.----.` ``..           Packages: 2098 (dpkg)  
    .::::-``:::::::::.`-:::-`        Shell: bash 5.1.4  
   -:::-`   .:::::::-`  `-:::-       Resolution: 3840x2160  
  `::.  `.--.`  `` `.---.``.::`      Terminal: /dev/pts/0  
      .::::::::`  -::::::::` `       CPU: BCM2711 (4) @ 1.500GHz  
.::` .:::::::::- `::::::::::``::.    Memory: 367MiB / 7847MiB  
-:::` ::::::::::.  ::::::::::.`:::-
::::  -::::::::.   `-::::::::  ::::                            
-::-   .-:::-.``....``.-::-.   -::-
.. ``       .::::::::.     `..`..
  -:::-`   -::::::::::`  .:::::`
  :::::::` -::::::::::` :::::::.
  .:::::::  -::::::::. ::::::::
   `-:::::`   ..--.`   ::::::.
     `...`  `...--..`  `...`
           .::::::::::
            `.-::::-`


9 - Check all your Rpi system.

bye.