Fred808 commited on
Commit
ffd513e
·
verified ·
1 Parent(s): 4563a27

Update generate_wireguard_config.py

Browse files
Files changed (1) hide show
  1. generate_wireguard_config.py +194 -81
generate_wireguard_config.py CHANGED
@@ -1,81 +1,194 @@
1
- import os
2
- import subprocess
3
-
4
- WG_DIR = "/etc/wireguard"
5
- SERVER_PRIVATE = os.path.join(WG_DIR, "privatekey")
6
- SERVER_PUBLIC = os.path.join(WG_DIR, "publickey")
7
- PEER_PRIVATE = os.path.join(WG_DIR, "peer1_privatekey")
8
- PEER_PUBLIC = os.path.join(WG_DIR, "peer1_publickey")
9
-
10
-
11
- def generate_keypair(private_path, public_path):
12
- priv = subprocess.check_output(["wg", "genkey"]).decode().strip()
13
- with open(private_path, "w") as f:
14
- f.write(priv)
15
- pub = subprocess.check_output(["wg", "pubkey"], input=priv.encode()).decode().strip()
16
- with open(public_path, "w") as f:
17
- f.write(pub)
18
- return priv, pub
19
-
20
- def main():
21
- os.makedirs(WG_DIR, exist_ok=True)
22
- # Generate keys
23
- server_priv, server_pub = generate_keypair(SERVER_PRIVATE, SERVER_PUBLIC)
24
- peer_priv, peer_pub = generate_keypair(PEER_PRIVATE, PEER_PUBLIC)
25
-
26
- # Server config
27
- wg0_conf = f"""
28
- [Interface]
29
- Address = 10.10.0.1/24
30
- ListenPort = 51820
31
- PrivateKey = {server_priv}
32
- PostUp = iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
33
- PostDown = iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE
34
-
35
- [Peer]
36
- PublicKey = {peer_pub}
37
- AllowedIPs = 10.10.0.2/32
38
- """
39
- with open(os.path.join(WG_DIR, "wg0.conf"), "w") as f:
40
- f.write(wg0_conf.strip())
41
-
42
- # Try to auto-detect public IP
43
- import socket
44
- import urllib.request
45
- public_ip = None
46
- try:
47
- # Try to get public IP from external service
48
- with urllib.request.urlopen('https://api.ipify.org') as response:
49
- public_ip = response.read().decode().strip()
50
- except Exception:
51
- # Fallback: get IP of eth0
52
- try:
53
- s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
54
- s.connect(("8.8.8.8", 80))
55
- public_ip = s.getsockname()[0]
56
- s.close()
57
- except Exception:
58
- public_ip = "<UNKNOWN>"
59
-
60
- print(f"[INFO] Detected public IP: {public_ip}")
61
-
62
- # Peer config
63
- peer_conf = f"""
64
- [Interface]
65
- PrivateKey = {peer_priv}
66
- Address = 10.10.0.2/24
67
- DNS = 1.1.1.1
68
-
69
- [Peer]
70
- PublicKey = {server_pub}
71
- Endpoint = {public_ip}:51820
72
- AllowedIPs = 0.0.0.0/0
73
- PersistentKeepalive = 25
74
- """
75
- with open(os.path.join(WG_DIR, "peer1.conf"), "w") as f:
76
- f.write(peer_conf.strip())
77
-
78
- print("✔ WireGuard config generated.")
79
-
80
- if __name__ == "__main__":
81
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import sys
4
+
5
+ WG_DIR = "/etc/wireguard"
6
+ SERVER_PRIVATE = os.path.join(WG_DIR, "privatekey")
7
+ SERVER_PUBLIC = os.path.join(WG_DIR, "publickey")
8
+ PEER_PRIVATE = os.path.join(WG_DIR, "peer1_privatekey")
9
+ PEER_PUBLIC = os.path.join(WG_DIR, "peer1_publickey")
10
+
11
+
12
+ def check_root():
13
+ """Check if running as root"""
14
+ if os.geteuid() != 0:
15
+ print(" This script must be run as root (use sudo)")
16
+ sys.exit(1)
17
+
18
+
19
+ def check_wireguard():
20
+ """Check if WireGuard is available"""
21
+ try:
22
+ subprocess.run(["wg", "--version"], check=True, capture_output=True)
23
+ print("✔ WireGuard tools found")
24
+ except (subprocess.CalledProcessError, FileNotFoundError):
25
+ print("❌ WireGuard tools not found. Install with:")
26
+ print(" Amazon Linux: sudo yum install wireguard-tools")
27
+ print(" Ubuntu/Debian: sudo apt install wireguard")
28
+ sys.exit(1)
29
+
30
+
31
+ def load_wireguard_module():
32
+ """Try to load WireGuard kernel module"""
33
+ try:
34
+ subprocess.run(["modprobe", "wireguard"], check=True, capture_output=True)
35
+ print("✔ WireGuard kernel module loaded")
36
+ except subprocess.CalledProcessError:
37
+ print("⚠ Warning: Could not load WireGuard kernel module")
38
+ print(" This might be a container/virtualized environment")
39
+ print(" WireGuard may still work with userspace implementation")
40
+
41
+
42
+ def enable_ip_forwarding():
43
+ """Enable IP forwarding if possible"""
44
+ try:
45
+ # Try to enable IP forwarding
46
+ subprocess.run(["sysctl", "-w", "net.ipv4.ip_forward=1"],
47
+ check=True, capture_output=True)
48
+ subprocess.run(["sysctl", "-w", "net.ipv6.conf.all.forwarding=1"],
49
+ check=True, capture_output=True)
50
+ print("✔ IP forwarding enabled")
51
+ except subprocess.CalledProcessError:
52
+ print("⚠ Warning: Could not enable IP forwarding")
53
+ print(" This might be a read-only filesystem or container")
54
+ print(" You may need to enable it manually or in the host system")
55
+
56
+
57
+ def generate_keypair(private_path, public_path):
58
+ """Generate WireGuard key pair"""
59
+ try:
60
+ priv = subprocess.check_output(["wg", "genkey"]).decode().strip()
61
+ with open(private_path, "w") as f:
62
+ f.write(priv)
63
+ os.chmod(private_path, 0o600) # Secure permissions
64
+
65
+ pub = subprocess.check_output(["wg", "pubkey"], input=priv.encode()).decode().strip()
66
+ with open(public_path, "w") as f:
67
+ f.write(pub)
68
+ os.chmod(public_path, 0o644)
69
+
70
+ return priv, pub
71
+ except Exception as e:
72
+ print(f"❌ Error generating keypair: {e}")
73
+ sys.exit(1)
74
+
75
+
76
+ def get_public_ip():
77
+ """Auto-detect public IP address"""
78
+ import socket
79
+ import urllib.request
80
+
81
+ # Try external service first
82
+ try:
83
+ with urllib.request.urlopen('https://api.ipify.org', timeout=5) as response:
84
+ return response.read().decode().strip()
85
+ except Exception:
86
+ pass
87
+
88
+ # Fallback to local interface IP
89
+ try:
90
+ s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
91
+ s.connect(("8.8.8.8", 80))
92
+ ip = s.getsockname()[0]
93
+ s.close()
94
+ return ip
95
+ except Exception:
96
+ return "<REPLACE_WITH_YOUR_PUBLIC_IP>"
97
+
98
+
99
+ def create_server_config(server_priv, peer_pub, interface="eth0"):
100
+ """Create server configuration"""
101
+ return f"""[Interface]
102
+ Address = 10.10.0.1/24
103
+ ListenPort = 51820
104
+ PrivateKey = {server_priv}
105
+ PostUp = iptables -t nat -A POSTROUTING -o {interface} -j MASQUERADE
106
+ PostUp = iptables -A FORWARD -i wg0 -j ACCEPT
107
+ PostUp = iptables -A FORWARD -o wg0 -j ACCEPT
108
+ PostDown = iptables -t nat -D POSTROUTING -o {interface} -j MASQUERADE
109
+ PostDown = iptables -D FORWARD -i wg0 -j ACCEPT
110
+ PostDown = iptables -D FORWARD -o wg0 -j ACCEPT
111
+
112
+ [Peer]
113
+ PublicKey = {peer_pub}
114
+ AllowedIPs = 10.10.0.2/32"""
115
+
116
+
117
+ def create_peer_config(peer_priv, server_pub, public_ip):
118
+ """Create peer configuration"""
119
+ return f"""[Interface]
120
+ PrivateKey = {peer_priv}
121
+ Address = 10.10.0.2/24
122
+ DNS = 1.1.1.1, 8.8.8.8
123
+
124
+ [Peer]
125
+ PublicKey = {server_pub}
126
+ Endpoint = {public_ip}:51820
127
+ AllowedIPs = 0.0.0.0/0
128
+ PersistentKeepalive = 25"""
129
+
130
+
131
+ def main():
132
+ print("🔧 WireGuard Configuration Generator")
133
+ print("=" * 40)
134
+
135
+ # Pre-flight checks
136
+ check_root()
137
+ check_wireguard()
138
+ load_wireguard_module()
139
+ enable_ip_forwarding()
140
+
141
+ # Create directory
142
+ try:
143
+ os.makedirs(WG_DIR, exist_ok=True)
144
+ print(f"✔ Created directory: {WG_DIR}")
145
+ except Exception as e:
146
+ print(f"❌ Could not create directory {WG_DIR}: {e}")
147
+ sys.exit(1)
148
+
149
+ # Generate keys
150
+ print("\n🔑 Generating keypairs...")
151
+ server_priv, server_pub = generate_keypair(SERVER_PRIVATE, SERVER_PUBLIC)
152
+ peer_priv, peer_pub = generate_keypair(PEER_PRIVATE, PEER_PUBLIC)
153
+ print("✔ Server and peer keypairs generated")
154
+
155
+ # Get public IP
156
+ public_ip = get_public_ip()
157
+ print(f"🌐 Detected public IP: {public_ip}")
158
+
159
+ # Create server config
160
+ server_config = create_server_config(server_priv, peer_pub)
161
+ try:
162
+ with open(os.path.join(WG_DIR, "wg0.conf"), "w") as f:
163
+ f.write(server_config)
164
+ os.chmod(os.path.join(WG_DIR, "wg0.conf"), 0o600)
165
+ print("✔ Server config written to wg0.conf")
166
+ except Exception as e:
167
+ print(f"❌ Error writing server config: {e}")
168
+ sys.exit(1)
169
+
170
+ # Create peer config
171
+ peer_config = create_peer_config(peer_priv, server_pub, public_ip)
172
+ try:
173
+ with open(os.path.join(WG_DIR, "peer1.conf"), "w") as f:
174
+ f.write(peer_config)
175
+ os.chmod(os.path.join(WG_DIR, "peer1.conf"), 0o600)
176
+ print("✔ Peer config written to peer1.conf")
177
+ except Exception as e:
178
+ print(f"❌ Error writing peer config: {e}")
179
+ sys.exit(1)
180
+
181
+ print("\n🎉 WireGuard configuration completed!")
182
+ print("\nNext steps:")
183
+ print("1. Start WireGuard: sudo wg-quick up wg0")
184
+ print("2. Enable at boot: sudo systemctl enable wg-quick@wg0")
185
+ print("3. Copy peer1.conf to your client device")
186
+ print("4. Check status: sudo wg show")
187
+
188
+ if public_ip == "<REPLACE_WITH_YOUR_PUBLIC_IP>":
189
+ print("\n⚠ Warning: Could not detect public IP!")
190
+ print(" Edit peer1.conf and replace the placeholder with your server's public IP")
191
+
192
+
193
+ if __name__ == "__main__":
194
+ main()