WireGuard + OpenVPN + Stunnel config

Installs WireGuard + OpenVPN + stunnel. Generates configs under /var/lib/vpn/clients. To use stunnel, install locally, copy stunnel-client.conf and modify client-direct.ovpn to point to 127.0.0.1 instead of your server. Make sure you replace the SSH authorized keys with your own.

Script Author

Rowan de Haas's avatar
Rowan de Haas
Script Author

Script Details

Created 2 months ago
Updated 2 months ago
Size 16 KB

Tags

Script Content

Raw
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
#cloud-config

# Secure VPN Server Cloud-Init Configuration
# 
# BEFORE DEPLOYMENT:
# 1. Replace the example SSH keys below with your actual public keys
# 2. Generate your SSH key: ssh-keygen -t ed25519 -C "your_email@example.com"
# 3. Copy your public key: cat ~/.ssh/id_ed25519.pub
# 4. Paste it in the ssh_authorized_keys sections below
#
# AFTER DEPLOYMENT:
# - Connect via SSH: ssh -p 2222 vpnuser@YOUR_SERVER_IP
# - Download VPN configs: scp -P 2222 -r vpnuser@YOUR_SERVER_IP:/var/lib/vpn/clients/ ./

# SSH Keys Configuration - Add your SSH public keys here
# Keys are defined in the users section below for the vpnuser account

package_update: true
package_upgrade: true

# User configuration
users:
  - name: vpnuser
    shell: /bin/bash
    sudo: ['ALL=(ALL) NOPASSWD:ALL']
    ssh_authorized_keys:
      # Replace these example keys with your actual SSH public keys:
      - "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIEXAMPLE1234567890abcdefghijklmnopqrstuvwxyz user@example.com"
      - "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAACAQEXAMPLE1234567890abcdefghijklmnopqrstuvwxyz user2@example.com"

packages:
  - wireguard
  - openvpn
  - easy-rsa
  - stunnel4
  - iptables-persistent
  - curl
  - fail2ban
  - unattended-upgrades

write_files:
  # Enable IP forwarding
  - path: /etc/sysctl.d/99-ip-forward.conf
    content: |
      net.ipv4.ip_forward=1
      net.ipv6.conf.all.forwarding=1
      # Security hardening
      net.ipv4.conf.all.send_redirects=0
      net.ipv4.conf.default.send_redirects=0
      net.ipv4.conf.all.accept_redirects=0
      net.ipv4.conf.default.accept_redirects=0
      net.ipv4.conf.all.secure_redirects=0
      net.ipv4.conf.default.secure_redirects=0
    permissions: '0644'

  # Secure firewall rules with DROP default policy
  - path: /etc/iptables/rules.v4
    content: |
      *filter
      :INPUT DROP [0:0]
      :FORWARD DROP [0:0]
      :OUTPUT ACCEPT [0:0]
      
      # Allow loopback
      -A INPUT -i lo -j ACCEPT
      -A OUTPUT -o lo -j ACCEPT
      
      # Allow established and related connections
      -A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
      -A FORWARD -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
      
      # Rate limiting for SSH (hardened port)
      -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --set --name ssh
      -A INPUT -p tcp --dport 2222 -m conntrack --ctstate NEW -m recent --update --seconds 60 --hitcount 4 --name ssh -j DROP
      -A INPUT -p tcp --dport 2222 -j ACCEPT
      
      # Rate limiting for VPN ports
      -A INPUT -p udp --dport 51820 -m conntrack --ctstate NEW -m limit --limit 10/min --limit-burst 20 -j ACCEPT
      -A INPUT -p tcp --dport 1194 -m conntrack --ctstate NEW -m limit --limit 10/min --limit-burst 20 -j ACCEPT  
      -A INPUT -p tcp --dport 443 -m conntrack --ctstate NEW -m limit --limit 20/min --limit-burst 50 -j ACCEPT
      
      # VPN traffic forwarding with security
      -A FORWARD -i wg0 -o eth0 -j ACCEPT
      -A FORWARD -i tun0 -o eth0 -j ACCEPT
      -A FORWARD -i eth0 -o wg0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
      -A FORWARD -i eth0 -o tun0 -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
      
      # Drop invalid packets
      -A INPUT -m conntrack --ctstate INVALID -j DROP
      -A FORWARD -m conntrack --ctstate INVALID -j DROP

      COMMIT
      
      *nat
      :PREROUTING ACCEPT [0:0]
      :INPUT ACCEPT [0:0]  
      :OUTPUT ACCEPT [0:0]
      :POSTROUTING ACCEPT [0:0]
      
      # NAT rules for VPN traffic
      -A POSTROUTING -s 10.66.66.0/24 ! -d 10.66.66.0/24 -o eth0 -j MASQUERADE
      -A POSTROUTING -s 10.8.0.0/24 ! -d 10.8.0.0/24 -o eth0 -j MASQUERADE
      
      COMMIT
    permissions: '0644'

  # Fail2ban configuration for VPN protection  
  - path: /etc/fail2ban/jail.d/vpn.conf
    content: |
      [sshd]
      enabled = true
      port = 2222
      filter = sshd
      logpath = /var/log/auth.log
      maxretry = 3
      bantime = 3600
      
      [openvpn]
      enabled = true
      port = 1194,443
      filter = openvpn
      logpath = /var/log/openvpn/server.log
      maxretry = 5
      bantime = 1800
    permissions: '0644'

  # Secure stunnel config template
  - path: /etc/stunnel/stunnel.conf.template
    content: |
      pid = /var/run/stunnel4/stunnel.pid
      setuid = stunnel4
      setgid = stunnel4
      foreground = no
      debug = 3
      output = /var/log/stunnel4/stunnel.log
      
      # Security options
      options = NO_SSLv2
      options = NO_SSLv3
      options = CIPHER_SERVER_PREFERENCE
      ciphersuites = TLS_AES_256_GCM_SHA384:TLS_CHACHA20_POLY1305_SHA256:TLS_AES_128_GCM_SHA256
      
      [openvpn-ssl]
      accept = 443
      connect = 127.0.0.1:1194
      cert = /etc/stunnel/stunnel.pem
      # Require client certificates for mutual TLS
      verify = 2
      CAfile = /etc/stunnel/ca.pem
    permissions: '0644'

  # Automatic security updates
  - path: /etc/apt/apt.conf.d/20auto-upgrades
    content: |
      APT::Periodic::Update-Package-Lists "1";
      APT::Periodic::Unattended-Upgrade "1";
    permissions: '0644'

  # SSH hardening configuration
  - path: /etc/ssh/sshd_config.d/99-hardening.conf
    content: |
      # Change default port (update firewall rules accordingly)
      Port 2222
      
      # Protocol and encryption
      Protocol 2
      
      # Authentication
      PermitRootLogin no
      PasswordAuthentication no
      ChallengeResponseAuthentication no
      PubkeyAuthentication yes
      AuthenticationMethods publickey
      
      # Login restrictions
      MaxAuthTries 3
      MaxSessions 2
      LoginGraceTime 30
      
      # Disable unused authentication methods
      KerberosAuthentication no
      GSSAPIAuthentication no
      UsePAM yes
      
      # Network settings
      ClientAliveInterval 300
      ClientAliveCountMax 2
      TCPKeepAlive no
      
      # Disable dangerous features
      AllowAgentForwarding no
      AllowTcpForwarding no
      X11Forwarding no
      PermitTunnel no
      GatewayPorts no
      PermitUserEnvironment no
      
      # Logging
      LogLevel VERBOSE
      SyslogFacility AUTH
      
      # Restrict users (adjust as needed)
      AllowUsers vpnuser
      DenyUsers root
      
      # Crypto settings
      Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr
      MACs hmac-sha2-256-etm@openssh.com,hmac-sha2-512-etm@openssh.com,hmac-sha2-256,hmac-sha2-512
      KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512
      
      # Host key algorithms
      HostKeyAlgorithms ssh-ed25519,ssh-ed25519-cert-v01@openssh.com,sk-ssh-ed25519@openssh.com,rsa-sha2-256,rsa-sha2-512
    permissions: '0644'

runcmd:
  # Apply sysctl settings
  - sysctl -p /etc/sysctl.d/99-ip-forward.conf
  
  # Auto-detect primary network interface
  - |
    PRIMARY_IFACE=$(ip route | awk '/default/ { print $5 ; exit }')
    sed -i "s/eth0/$PRIMARY_IFACE/g" /etc/iptables/rules.v4
  
  # Load iptables rules
  - iptables-restore < /etc/iptables/rules.v4
  - systemctl enable netfilter-persistent

  # Create VPN directories (user is created automatically by cloud-init)
  - mkdir -p /var/lib/vpn/clients /var/lib/vpn/server
  - chmod 700 /var/lib/vpn /var/lib/vpn/clients /var/lib/vpn/server
  - chown -R vpnuser:vpnuser /var/lib/vpn

  # === WireGuard setup ===
  - mkdir -p /etc/wireguard
  - chmod 700 /etc/wireguard
  
  # Generate WireGuard keys with better entropy
  - |
    umask 077
    wg genkey > /etc/wireguard/server.key
    wg pubkey < /etc/wireguard/server.key > /etc/wireguard/server.pub
    wg genkey > /var/lib/vpn/clients/wg-client.key  
    wg pubkey < /var/lib/vpn/clients/wg-client.key > /var/lib/vpn/clients/wg-client.pub
    chown vpnuser:vpnuser /var/lib/vpn/clients/wg-client.*

  # Create WireGuard server config
  - |
    SERVER_KEY=$(cat /etc/wireguard/server.key)
    CLIENT_PUB=$(cat /var/lib/vpn/clients/wg-client.pub)
    cat > /etc/wireguard/wg0.conf <> vars < /var/lib/vpn/client_name.txt
  
  - openvpn --genkey secret /etc/openvpn/ta.key
  - chmod 600 /etc/openvpn/ta.key /etc/openvpn/easy-rsa/pki/private/*

  # Secure OpenVPN server config
  - |
    mkdir -p /var/log/openvpn
    cat > /etc/openvpn/server.conf <<'EOF'
    port 1194
    proto tcp
    dev tun
    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
    
    # Strong crypto
    auth SHA512
    cipher AES-256-GCM
    ncp-ciphers AES-256-GCM:AES-128-GCM
    tls-version-min 1.2
    tls-auth /etc/openvpn/ta.key 0
    
    topology subnet
    server 10.8.0.0 255.255.255.0
    
    # Security options
    remote-cert-tls client
    tls-server
    
    # Networking
    push "redirect-gateway def1 bypass-dhcp"
    push "dhcp-option DNS 9.9.9.9"
    push "dhcp-option DNS 149.112.112.112"
    
    keepalive 10 120
    persist-key  
    persist-tun
    
    # Privileges
    user nobody
    group nogroup
    
    # Logging
    status /var/log/openvpn/status.log
    log-append /var/log/openvpn/server.log
    verb 3
    mute 20
    
    explicit-exit-notify 1
    EOF

  - systemctl enable openvpn@server
  - systemctl start openvpn@server

  # === Secure stunnel setup ===
  - |
    # Get public IP with fallback
    PUBLIC_IP=$(curl -s --max-time 10 ifconfig.me || curl -s --max-time 10 icanhazip.com || hostname -I | awk '{print $1}')
    
    # Generate stunnel server certificate using OpenVPN CA (not self-signed)
    cd /etc/openvpn/easy-rsa
    STUNNEL_SERVER="stunnel-server-$(openssl rand -hex 4)"
    ./easyrsa gen-req $STUNNEL_SERVER nopass
    ./easyrsa sign-req server $STUNNEL_SERVER
    
    # Create stunnel certificate bundle (cert + key)
    cat /etc/openvpn/easy-rsa/pki/issued/$STUNNEL_SERVER.crt \
        /etc/openvpn/easy-rsa/pki/private/$STUNNEL_SERVER.key > /etc/stunnel/stunnel.pem
    chmod 600 /etc/stunnel/stunnel.pem
    
    # Copy CA for client verification (same CA as OpenVPN)
    cp /etc/openvpn/easy-rsa/pki/ca.crt /etc/stunnel/ca.pem
    
    # Generate client certificate for stunnel mutual TLS
    STUNNEL_CLIENT="stunnel-client-$(openssl rand -hex 4)"
    ./easyrsa gen-req $STUNNEL_CLIENT nopass
    ./easyrsa sign-req client $STUNNEL_CLIENT
    
    # Create client certificate bundle for stunnel
    cat /etc/openvpn/easy-rsa/pki/issued/$STUNNEL_CLIENT.crt \
        /etc/openvpn/easy-rsa/pki/private/$STUNNEL_CLIENT.key > /var/lib/vpn/clients/client.pem
    chmod 600 /var/lib/vpn/clients/client.pem
    
    # Use secure stunnel config
    cp /etc/stunnel/stunnel.conf.template /etc/stunnel/stunnel.conf

  # Start services with proper ordering
  - systemctl enable stunnel4 fail2ban
  - sleep 5  # Allow OpenVPN to fully start
  - systemctl start stunnel4 
  - systemctl start fail2ban

  # Generate client configurations securely  
  - |
    PUBLIC_IP=$(curl -s --max-time 10 ifconfig.me || curl -s --max-time 10 icanhazip.com || hostname -I | awk '{print $1}')
    CLIENT_NAME=$(cat /var/lib/vpn/client_name.txt)
    
    # WireGuard client config
    CLIENT_KEY=$(cat /var/lib/vpn/clients/wg-client.key)
    SERVER_PUB=$(cat /etc/wireguard/server.pub)
    cat > /var/lib/vpn/clients/wg-client.conf < /var/lib/vpn/clients/client-direct.ovpn <
    $(cat /etc/openvpn/easy-rsa/pki/ca.crt)
    
    
    $(sed -n '/BEGIN CERTIFICATE/,/END CERTIFICATE/p' /etc/openvpn/easy-rsa/pki/issued/$CLIENT_NAME.crt)
    
    
    $(cat /etc/openvpn/easy-rsa/pki/private/$CLIENT_NAME.key)
    
    
    $(cat /etc/openvpn/ta.key)
    
    EOF
    
    # Secure stunnel client config
    cat > /var/lib/vpn/clients/stunnel-client.conf < /var/lib/vpn/clients/SECURITY-README.md </dev/null || true
    chmod 640 /var/log/stunnel4/* 2>/dev/null || true
    
    # Remove unnecessary packages
    apt autoremove -y
    
    # Update package database
    apt update

  # Status check
  - sleep 15
  - systemctl status wg-quick@wg0 openvpn@server stunnel4 fail2ban --no-pager

How to Use This Script

Cloud Provider Examples

Amazon EC2

aws ec2 run-instances
  --image-id ami-12345678
  --instance-type t3.micro
  --user-data file://script.yaml

DigitalOcean

doctl compute droplet create
  --image ubuntu-22-04-x64
  --size s-1vcpu-1gb
  --user-data-file script.yaml
  my-droplet

Google Cloud

gcloud compute instances create
  my-instance
  --metadata-from-file
  user-data=script.yaml