A practical guid based on a real OpenVPN 2.6.14 installation on Debian 13 (Trixie), alongside ISPConfig, Apache, DNS and mail services. It covers certificate-based authentication, unattended startup, persistent forwarding and NAT, client profiles, troubleshooting and an optional three-session limit per certificate.
1. Server architecture
| Parameter | Value |
|---|---|
| OS | Debian 13 Trixie |
| OpenVPN | 2.6.14 (observed installation) |
| Authentication | Easy-RSA certificates |
| Protocol / port | UDP 1194 |
| External interface | eth0 |
| Tunnel interface | tun0 |
| VPN subnet | 10.9.8.0/24 |
| VPN gateway | 10.9.8.1 with subnet topology |
| Firewall | UFW, managed alongside ISPConfig |
| Backend | iptables-nft |
| Optional session limit | 3 per certificate Common Name (CN) |
- Windows / mobile / Cudy router
- OpenVPN server
- tun0: 10.9.8.0/24
- UFW forwarding and NAT
- eth0
- Internet
Run commands as root. Substitute your own server hostname, network interface and subnet as necessary. Back up existing configuration before modifying a production server, and use an SSH connection independent of the VPN.
2. Install OpenVPN and Easy-RSA
apt update
apt install openvpn easy-rsa openssl python3 nmap tcpdump
openvpn --version
ls -l /dev/net/tun
If the TUN device is unavailable, try modprobe tun. On a virtual server, the hosting provider may also need to enable TUN access.
3. Create the certificate authority and certificates
For a new installation only:
make-cadir /etc/openvpn/easy-rsa
cd /etc/openvpn/easy-rsa
./easyrsa init-pki
./easyrsa build-ca
./easyrsa build-server-full server nopass
./easyrsa build-client-full vpn1
./easyrsa gen-dh
./easyrsa gen-crl
openvpn --genkey secret /etc/openvpn/ta.key
chmod 600 /etc/openvpn/ta.key
Choose a strong CA password. Do not initialize a PKI that already contains active certificates. Keep the CA private key protected, ideally offline. For an unattended client such as a router, use ./easyrsa build-client-full vpn1 nopass instead of the password-protected client creation command above. Use unique certificate names for different users or devices whenever possible.
The nopass option on the server key permits unattended service startup. It does not change VPN traffic encryption, but removes password encryption of the key at rest.
4. Directory structure
/etc/openvpn/
├── server.conf
├── ta.key
├── scripts/
└── easy-rsa/
├── easyrsa
└── pki/
├── ca.crt
├── dh.pem
├── crl.pem
├── issued/
│ ├── server.crt
│ └── vpn1.crt
└── private/
├── ca.key
├── server.key
└── vpn1.key
Protect all private keys and the shared TLS authentication key.
5. Configure the OpenVPN server
Create /etc/openvpn/server.conf with the following reference configuration:
port 1194
proto udp4
dev tun0
topology subnet
ca /etc/openvpn/easy-rsa/pki/ca.crt
cert /etc/openvpn/easy-rsa/pki/issued/server.crt
key /etc/openvpn/easy-rsa/pki/private/server.key
dh /etc/openvpn/easy-rsa/pki/dh.pem
verify-client-cert require
remote-cert-tls client
crl-verify /etc/openvpn/easy-rsa/pki/crl.pem
tls-auth /etc/openvpn/ta.key 0
tls-version-min 1.2
server 10.9.8.0 255.255.255.0
push "redirect-gateway def1 bypass-dhcp"
push "dhcp-option DNS 1.1.1.1"
push "dhcp-option DNS 8.8.8.8"
data-ciphers AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305
auth SHA256
keepalive 10 60
persist-key
persist-tun
max-clients 100
status /var/log/openvpn/openvpn-status.log 10
status-version 2
verb 3
explicit-exit-notify 1
mkdir -p /var/log/openvpn
chmod 600 /etc/openvpn/server.conf
chmod 600 /etc/openvpn/easy-rsa/pki/private/server.key
This is a modern IPv4 full-tunnel example. IPv6 requires separate routing or leak-prevention measures. Older routers may need compatibility options. DNS server choices are examples, not mandatory settings.
6. Enable automatic startup
The configuration layout used in this installation is /etc/openvpn/server.conf with openvpn@server.service.
systemctl enable --now openvpn@server.service
systemctl status openvpn@server.service
journalctl -u openvpn@server.service -n 50 --no-pager
ss -ulnp | grep ':1194'
ip -br addr
Successful initialization includes Initialization Sequence Completed, a UDP socket on port 1194 and a tun0 interface with address 10.9.8.1/24.
Debian also supports /etc/openvpn/server/server.conf with openvpn-server@server.service. Do not start both instances for the same configuration.
7. Troubleshoot a closed port and encrypted server key
Nmap scans TCP by default. For UDP, run:
nmap -sU -p 1194 127.0.0.1
ss -ulnp | grep ':1194'
systemctl status openvpn@server.service -l --no-pager
journalctl -u openvpn@server.service -n 100 --no-pager
| Nmap result | Interpretation |
|---|---|
| open | Service responded |
| open|filtered | No response; common for OpenVPN UDP |
| closed | No listener or explicit rejection |
| filtered | Filtering detected |
In the actual installation, systemd reported the process as running, but no socket or TUN interface existed. The process tree revealed:
/usr/bin/systemd-ask-password --icon network-vpn --timeout=0 "Enter Private Key Password:"
OpenVPN was waiting indefinitely for the encrypted private key password. The temporary solution was:
systemd-tty-ask-password-agent --query
For permanent unattended startup, preserve the original encrypted key and create a passwordless copy:
cp -a /etc/openvpn/server.conf /etc/openvpn/server.conf.bak
umask 077
openssl pkey \
-in /etc/openvpn/easy-rsa/pki/private/server.key \
-out /etc/openvpn/easy-rsa/pki/private/server-nopass.key
chown root:root /etc/openvpn/easy-rsa/pki/private/server-nopass.key
chmod 600 /etc/openvpn/easy-rsa/pki/private/server-nopass.key
openssl pkey -in /etc/openvpn/easy-rsa/pki/private/server-nopass.key -check -noout
Replace the key directive in /etc/openvpn/server.conf with:
key /etc/openvpn/easy-rsa/pki/private/server-nopass.key
systemctl restart openvpn@server.service
ss -ulnp | grep ':1194'
The server certificate and client profiles remain unchanged. The new key is unencrypted at rest; protect permissions and backups.
8. Enable persistent IPv4 forwarding on Debian 13
Debian 13 no longer automatically honors /etc/sysctl.conf through its standard systemd boot configuration. Use a dedicated drop-in:
printf 'net.ipv4.ip_forward = 1\n' > /etc/sysctl.d/99-openvpn.conf
sysctl --system
sysctl net.ipv4.ip_forward
cat /proc/sys/net/ipv4/ip_forward
Expected value: 1.
If forwarding is reset, inspect conflicting settings in /etc/sysctl.d, /usr/lib/sysctl.d, /run/sysctl.d and /etc/ufw/sysctl.conf.
9. Preserve ISPConfig firewall management
Determine which firewall manager is active:
systemctl is-active nftables firewalld ufw netfilter-persistent
iptables --version
ufw status verbose
The actual installation used UFW, with iptables 1.8.11 (nf_tables). The standalone nftables, firewalld and netfilter-persistent services were inactive.
Do not enable a competing nftables service, flush the ruleset, or overwrite /etc/nftables.conf on this UFW-managed server.
Open UDP port 1194 using ISPConfig’s firewall configuration. On a standalone UFW server, the equivalent is:
ufw allow 1194/udp
Back up UFW before editing:
BACKUP="/root/ufw-backup-$(date +%Y%m%d-%H%M%S)"
mkdir -m 700 "$BACKUP"
cp -a /etc/ufw "$BACKUP/"
cp -a /etc/default/ufw "$BACKUP/ufw-default"
nft list ruleset > "$BACKUP/nftables-ruleset.txt"
10. Configure persistent forwarding rules
ufw route allow in on tun0 out on eth0 from 10.9.8.0/24 to any
UFW normally permits related and established return traffic automatically. Check:
grep 'ufw-before-forward.*RELATED,ESTABLISHED' /etc/ufw/before.rules
grep DEFAULT_FORWARD_POLICY /etc/default/ufw
Keep the existing restrictive default forwarding policy. The explicit VPN rule is preferable to allowing unrestricted forwarding.
11. Configure permanent NAT masquerading
Inspect existing NAT rules:
grep -nE '^\*nat|^:POSTROUTING|MASQUERADE|SNAT' /etc/ufw/before.rules
Edit /etc/ufw/before.rules. If there is no existing NAT section, insert this block before *filter:
# BEGIN OPENVPN NAT RULES
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -s 10.9.8.0/24 -o eth0 -j MASQUERADE
COMMIT
# END OPENVPN NAT RULES
If a NAT section already exists, add the rule inside it before its COMMIT, ensuring the necessary chain exists. Preserve all original UFW rules.
The original installation encountered Bad argument '*filter' because the NAT section lacked COMMIT. Each table must be committed separately. The structure must be:
*nat
... NAT rules ...
COMMIT
*filter
... existing UFW filter rules ...
COMMIT
In /etc/ufw/sysctl.conf, uncomment or add:
net/ipv4/ip_forward=1
Validate before reloading:
iptables-restore --test < /etc/ufw/before.rules
After confirming SSH access remains permitted, reload:
ufw reload
iptables -t nat -L POSTROUTING -n -v
iptables -L ufw-user-forward -n -v
sysctl net.ipv4.ip_forward
ufw status verbose
Check that ISPConfig preserves the custom rules after subsequent firewall updates. If manual nftables rules were previously added, inspect them individually; do not delete complete shared tables.
12. Generate client profiles
An inline .ovpn profile contains the CA certificate, client certificate, client private key and TLS authentication key. The server and client protocol, authentication digest and TLS key direction must match.
Create /etc/openvpn/generate-client.sh:
#!/bin/bash
set -euo pipefail
umask 077
CLIENT="${1:?Usage: generate-client.sh CLIENT SERVER}"
SERVER="${2:?Specify server IP or hostname}"
PKI="/etc/openvpn/easy-rsa/pki"
[[ "$CLIENT" =~ ^[a-zA-Z0-9_-]+$ ]] || exit 1
[[ "$SERVER" =~ ^[a-zA-Z0-9.-]+$ ]] || exit 1
OUTPUT="/root/${CLIENT}.ovpn"
{
cat <<PROFILE
client
dev tun
proto udp4
remote $SERVER 1194
resolv-retry infinite
nobind
persist-key
persist-tun
remote-cert-tls server
data-ciphers AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305
auth SHA256
key-direction 1
verb 3
PROFILE
echo '<ca>'
cat "$PKI/ca.crt"
echo '</ca>'
echo '<cert>'
openssl x509 -in "$PKI/issued/$CLIENT.crt"
echo '</cert>'
echo '<key>'
cat "$PKI/private/$CLIENT.key"
echo '</key>'
echo '<tls-auth>'
cat /etc/openvpn/ta.key
echo '</tls-auth>'
} > "$OUTPUT"
chmod 600 "$OUTPUT"
echo "Configuration created: $OUTPUT"
chmod 700 /etc/openvpn/generate-client.sh
/etc/openvpn/generate-client.sh vpn1 YOUR_SERVER_IP
Transfer /root/vpn1.ovpn securely. It contains credentials and must not be published or committed to source control.
13. Connect from Windows
Install OpenVPN Connect, import vpn1.ovpn and connect. Verify that the client receives an address in 10.9.8.0/24, can access the Internet and uses the server’s public IPv4 address for full-tunnel traffic.
14. Connect from a Cudy router
Open the router administration interface, locate VPN client settings, choose OpenVPN and import the profile. Exact menu names depend on model and firmware.
Older firmware may require legacy cipher compatibility. For example, if the client requires AES-128-CBC, the server can be configured with:
data-ciphers AES-256-GCM:AES-128-GCM:CHACHA20-POLY1305:AES-128-CBC
data-ciphers-fallback AES-128-CBC
The client may also require matching cipher, digest and TLS authentication options. Only enable legacy compatibility when necessary. CBC ciphers can disable DCO acceleration.
15. Allow multiple simultaneous connections
OpenVPN normally replaces an existing connection when another session uses the same certificate CN. To permit concurrent sessions, add:
duplicate-cn
Remove ifconfig-pool-persist if present, because it is incompatible with duplicate-cn. The max-clients directive sets the total server limit, not a per-certificate limit.
Prefer separate certificates for individual devices when possible, because shared certificates weaken individual revocation and accountability.
16. Optional: limit each certificate to three simultaneous connections
A custom Python/SQLite hook can register active sessions and reject a fourth connection. Unlike a periodically updated status file, an SQLite transaction allows counting and inserting a session atomically.
The following is the expanded reference implementation from the article, not the exact original script tested on the server. It records the remote IP and port to reduce erroneous deletion of unrelated session records. Endpoint changes and failed disconnect hooks can cause stale records, so test before production use.
mkdir -p /etc/openvpn/scripts
chmod 755 /etc/openvpn/scripts
cat > /etc/openvpn/scripts/client-limit.py <<'PYTHON'
#!/usr/bin/python3
import os
import sys
import sqlite3
import ipaddress
import syslog
MAX_CONNECTIONS = 3
DATABASE = "/run/openvpn-limit/sessions.db"
syslog.openlog("openvpn-limit")
try:
action = sys.argv[1]
cn = os.environ.get("common_name", "")
vpn_ip = os.environ.get("ifconfig_pool_remote_ip", "")
remote_ip = os.environ.get("trusted_ip", "")
remote_port = os.environ.get("trusted_port", "")
if not cn or not remote_ip or not remote_port:
raise ValueError("Missing connection identity")
vpn_ip = str(ipaddress.IPv4Address(vpn_ip))
with sqlite3.connect(DATABASE, timeout=5) as db:
db.execute("""
CREATE TABLE IF NOT EXISTS sessions (
vpn_ip TEXT PRIMARY KEY,
common_name TEXT NOT NULL,
remote_ip TEXT NOT NULL,
remote_port TEXT NOT NULL
)
""")
db.execute("BEGIN IMMEDIATE")
if action == "connect":
count = db.execute(
"SELECT COUNT(*) FROM sessions WHERE common_name = ?",
(cn,)
).fetchone()[0]
if count >= MAX_CONNECTIONS:
syslog.syslog(syslog.LOG_WARNING,
f"DENIED: {cn} - {count}/{MAX_CONNECTIONS}")
sys.exit(1)
db.execute("INSERT INTO sessions VALUES (?, ?, ?, ?)",
(vpn_ip, cn, remote_ip, remote_port))
db.commit()
syslog.syslog(syslog.LOG_INFO,
f"ACCEPTED: {cn} - {count + 1}/{MAX_CONNECTIONS}")
elif action == "disconnect":
db.execute(
"DELETE FROM sessions WHERE vpn_ip = ? AND common_name = ? "
"AND remote_ip = ? AND remote_port = ?",
(vpn_ip, cn, remote_ip, remote_port)
)
db.commit()
syslog.syslog(syslog.LOG_INFO, f"DISCONNECTED: {cn} - {vpn_ip}")
else:
raise ValueError("Invalid action")
except Exception as error:
syslog.syslog(syslog.LOG_ERR, str(error))
sys.exit(1)
sys.exit(0)
PYTHON
chown root:root /etc/openvpn/scripts/client-limit.py
chmod 755 /etc/openvpn/scripts/client-limit.py
python3 -m py_compile /etc/openvpn/scripts/client-limit.py
Check the OpenVPN process identity:
ps -o user,group,cmd -p "$(systemctl show -p MainPID --value openvpn@server.service)"
The observed server ran as root. Create a systemd override with systemctl edit openvpn@server.service:
[Service]
RuntimeDirectory=openvpn-limit
RuntimeDirectoryMode=0700
ExecStartPre=/usr/bin/rm -f /run/openvpn-limit/sessions.db /run/openvpn-limit/sessions.db-journal
ReadWritePaths=/run/openvpn-limit
This is a reference override for the root-run service. If OpenVPN drops privileges, adjust directory ownership so the actual hook user can write to it. Do not make the directory globally writable.
Add to /etc/openvpn/server.conf, integrating any existing hooks instead of blindly replacing them:
duplicate-cn
script-security 2
client-connect "/usr/bin/python3 /etc/openvpn/scripts/client-limit.py connect"
client-disconnect "/usr/bin/python3 /etc/openvpn/scripts/client-limit.py disconnect"
systemctl daemon-reload
systemctl restart openvpn@server.service
journalctl -t openvpn-limit -f
Test three sessions with the same certificate, then attempt a fourth. It should be rejected with AUTH_FAILED. Disconnect one admitted session and retry. Also test a different CN, abrupt disconnection, reconnects, endpoint changes and service restarts. Adjust MAX_CONNECTIONS for future connection attempts as needed.
17. Troubleshoot AUTH_FAILED after adding scripts
In the original installation the server validated the client certificate, completed TLS negotiation and allocated 10.9.8.2, but then logged:
WARNING: Failed running command (--client-connect): could not execute external program
WARNING: Failed running command (--client-disconnect): could not execute external program
SENT CONTROL [vpn1]: 'AUTH_FAILED'
The connection-limiting script had been copied incompletely: its shebang, imports and initial definitions were missing. Replacing the complete script and invoking Python explicitly fixed the observed connection failure.
Diagnostic commands:
journalctl -t openvpn-limit -n 50 --no-pager
journalctl -u openvpn@server.service -n 80 --no-pager
which python3
head -n 15 /etc/openvpn/scripts/client-limit.py
namei -l /etc/openvpn/scripts/client-limit.py
ls -ld /run/openvpn-limit
python3 -m py_compile /etc/openvpn/scripts/client-limit.py
systemctl cat openvpn@server.service
If necessary, temporarily comment out client-connect and client-disconnect and restart the service to restore connectivity. The limit will be disabled until the hooks are restored. Do not regenerate valid certificates to solve a hook execution failure.
18. Monitor active connections
cat /var/log/openvpn/openvpn-status.log
watch -n 2 cat /var/log/openvpn/openvpn-status.log
journalctl -u openvpn@server.service -f
journalctl -t openvpn-limit -f
If the optional connection limit is installed, query its database:
python3 - <<'PY'
import sqlite3
with sqlite3.connect("file:/run/openvpn-limit/sessions.db?mode=ro", uri=True) as db:
print(f"{'CLIENT':25} {'CONNECTIONS':>12}")
print('-' * 40)
for cn, count in db.execute('''
SELECT common_name, COUNT(*) FROM sessions
GROUP BY common_name ORDER BY common_name
'''):
print(f"{cn:25} {count:>10}/3")
PY
The database is created on the first hook invocation. Compare it with the OpenVPN status file to detect stale session records.
19. Create additional clients
cd /etc/openvpn/easy-rsa
./easyrsa build-client-full vpn2
/etc/openvpn/generate-client.sh vpn2 YOUR_SERVER_IP
No server restart is required to admit a newly issued certificate under the existing CA.
20. Revoke a client certificate
cd /etc/openvpn/easy-rsa
./easyrsa revoke vpn1
./easyrsa gen-crl
Ensure the configuration contains crl-verify /etc/openvpn/easy-rsa/pki/crl.pem and that the CRL is readable by OpenVPN. The updated CRL rejects new connections from revoked certificates. Restart the server if you need to terminate all existing sessions immediately; this disconnects other clients too. Renew the CRL before expiration.
21. Verify after reboot
During a maintenance window, perform a controlled server reboot. After reconnecting through SSH:
systemctl is-active openvpn@server.service
systemctl is-enabled openvpn@server.service
sysctl net.ipv4.ip_forward
ss -ulnp | grep ':1194'
ip -br addr
iptables -t nat -L POSTROUTING -n -v
iptables -L ufw-user-forward -n -v
ufw status verbose
journalctl -u openvpn@server.service -b -n 30 --no-pager
If the optional limiter is configured, also verify ls -ld /run/openvpn-limit.
Installation checklist
- To verify: OpenVPN and Easy-RSA installed
- To verify: CA created and protected
- To verify: Server and client certificates generated
- To verify: Server starts without a password prompt
- To verify: Automatic startup enabled
- To verify: UDP port 1194 listening and permitted
- To verify: TUN interface initialized
- To verify: IPv4 forwarding survives reboot
- To verify: UFW forwarding and NAT persist
- To verify: ISPConfig firewall management preserved
- To verify: Windows connectivity verified
- To verify: Router connectivity verified, if applicable
- To verify: Optional three-session limit and cleanup tested
- To verify: Certificate revocation configured
- To verify: Controlled reboot tested
22. Common problems and solutions
| Problem | Probable cause / solution |
|---|---|
| Nmap reports port closed | Check UDP scan and actual listening socket |
| Service running but no socket | Check for encrypted private key password prompt |
| Connected without Internet | Check forwarding, NAT, routes and DNS |
| Forwarding resets after reboot | Use /etc/sysctl.d/99-openvpn.conf and verify UFW sysctl |
Bad argument '*filter' |
Missing COMMIT in preceding NAT section |
| Router cannot connect | Verify cipher, digest and TLS settings |
| Existing session replaced | Enable duplicate-cn if intentionally sharing a CN |
AUTH_FAILED despite valid certificate |
Check server-side connection hook logs |
| Python hook produces no logs | Check executable, complete script, interpreter and permissions |
| Disconnected client still occupies slot | Check keepalive, disconnect hook and stale database records |
For external connectivity problems, run tcpdump -ni any udp port 1194 while attempting a connection. Incoming packets establish that traffic is reaching the server, but do not by themselves prove successful authentication.
Conclusion
OpenVPN can operate alongside existing production services on Debian. The real installation demonstrated the importance of unattended private key handling, Debian 13 sysctl changes, preserving ISPConfig firewall management and making NAT and forwarding rules persistent. Custom connection hooks can add per-certificate session limits, but require careful testing and monitoring.
