Skip to content

Commit fe70a31

Browse files
authored
Update wg-add.sh
1 parent 37f7be2 commit fe70a31

File tree

1 file changed

+51
-61
lines changed

1 file changed

+51
-61
lines changed

wireguard/wg-add.sh

Lines changed: 51 additions & 61 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,11 @@
11
#!/bin/bash
2+
set -euo pipefail
23
# =========================================
3-
# CREATE WIREGUARD USER - IMPROVED VERSION
4+
# CREATE WIREGUARD USER
45
# =========================================
56

67
# ---------- Colors ----------
7-
red='\e[1;31m'
8-
green='\e[0;32m'
9-
yellow='\e[1;33m'
10-
blue='\e[1;34m'
11-
white='\e[1;37m'
12-
nc='\e[0m'
8+
red='\e[1;31m'; green='\e[0;32m'; yellow='\e[1;33m'; blue='\e[1;34m'; nc='\e[0m'
139

1410
# ---------- Functions ----------
1511
log_error() { echo -e "${red}$1${nc}"; }
@@ -25,6 +21,7 @@ fi
2521

2622
if ! systemctl is-active --quiet wg-quick@wg0; then
2723
log_warn "WireGuard service is not active. Starting..."
24+
systemctl daemon-reload
2825
if ! systemctl start wg-quick@wg0; then
2926
log_error "Failed to start wg-quick@wg0"
3027
exit 1
@@ -38,8 +35,8 @@ if [[ -z "$user" ]]; then
3835
log_error "Username cannot be empty!"
3936
exit 1
4037
fi
38+
user=$(echo "$user" | tr '[:upper:]' '[:lower:]')
4139

42-
# Validasi username (hanya huruf, angka, underscore)
4340
if [[ ! "$user" =~ ^[a-zA-Z0-9_]+$ ]]; then
4441
log_error "Username can only contain letters, numbers, and underscores"
4542
exit 1
@@ -59,55 +56,43 @@ priv_key=$(wg genkey)
5956
pub_key=$(echo "$priv_key" | wg pubkey)
6057
psk=$(wg genpsk)
6158

62-
# ---------- Improved IP Assignment ----------
59+
# ---------- Dynamic IP Allocation ----------
6360
find_available_ip() {
64-
local base_network="10.88.88"
61+
local base_network
62+
base_network=$(grep -m1 Address /etc/wireguard/wg0.conf | cut -d'=' -f2 | tr -d ' ' | cut -d'/' -f1 | cut -d'.' -f1-3)
6563
local used_ips=()
66-
67-
# Get all currently used IPs
68-
if command -v wg >/dev/null 2>&1; then
69-
# Try to get from running interface first
70-
used_ips+=($(wg show wg0 allowed-ips 2>/dev/null | awk '{print $2}' | cut -d'.' -f4 | cut -d'/' -f1))
71-
fi
72-
73-
# Also check config file
74-
if [[ -f /etc/wireguard/wg0.conf ]]; then
75-
used_ips+=($(grep AllowedIPs /etc/wireguard/wg0.conf | awk '{print $3}' | cut -d'.' -f4 | cut -d'/' -f1))
76-
fi
77-
78-
# Remove duplicates and sort
64+
65+
used_ips+=($(wg show wg0 allowed-ips 2>/dev/null | awk '{print $2}' | cut -d'.' -f4 | cut -d'/' -f1))
66+
used_ips+=($(grep AllowedIPs /etc/wireguard/wg0.conf | awk '{print $3}' | cut -d'.' -f4 | cut -d'/' -f1))
7967
used_ips=($(printf "%s\n" "${used_ips[@]}" | sort -nu))
80-
81-
# Find first available IP starting from 2
68+
8269
for i in {2..254}; do
83-
if [[ ! " ${used_ips[@]} " =~ " $i " ]]; then
84-
echo "$i"
70+
if [[ ! " ${used_ips[*]} " =~ " $i " ]]; then
71+
echo "$base_network.$i"
8572
return 0
8673
fi
8774
done
88-
89-
log_error "No available IP addresses in range"
75+
log_error "No available IP addresses in range."
9076
exit 1
9177
}
9278

93-
ip_suffix=$(find_available_ip)
94-
client_ip="10.88.88.$ip_suffix/32"
95-
79+
client_ip="$(find_available_ip)/32"
9680
log_info "Assigned IP: $client_ip"
9781

98-
# ---------- Get Server Info ----------
82+
# ---------- Server Info ----------
9983
log_info "Retrieving server information..."
10084
server_ip=$(curl -s -4 ipv4.icanhazip.com || curl -s -4 ifconfig.me || curl -s -4 icanhazip.com)
101-
server_port=$(grep ListenPort /etc/wireguard/wg0.conf | awk '{print $3}')
102-
server_pubkey=$(wg show wg0 public-key 2>/dev/null)
85+
server_ip=$(echo "$server_ip" | tr -d '\r')
86+
server_port=$(grep -m1 ListenPort /etc/wireguard/wg0.conf | awk '{print $3}')
87+
server_pubkey=$(wg show wg0 | awk '/public key/ {print $3; exit}')
10388

10489
if [[ -z "$server_ip" ]]; then
105-
log_warn "Could not detect public IP automatically"
106-
read -rp "Please enter server public IP: " server_ip
107-
if [[ -z "$server_ip" ]]; then
108-
log_error "Server IP is required"
109-
exit 1
110-
fi
90+
log_warn "Could not detect public IP automatically"
91+
read -rp "Please enter server public IP: " server_ip
92+
if [[ -z "$server_ip" ]]; then
93+
log_error "Server IP is required"
94+
exit 1
95+
fi
11196
fi
11297

11398
if [[ -z "$server_port" || -z "$server_pubkey" ]]; then
@@ -118,13 +103,13 @@ fi
118103
# ---------- Backup Original Config ----------
119104
config_backup="/etc/wireguard/wg0.conf.backup.$(date +%Y%m%d_%H%M%S)"
120105
cp /etc/wireguard/wg0.conf "$config_backup"
121-
log_info "Config backed up to: $config_backup"
106+
log_info "Backup created: $config_backup"
122107

123108
# ---------- Append to Server Config ----------
124-
log_info "Updating server configuration..."
109+
log_info "Adding new peer to server config..."
125110
cat >> /etc/wireguard/wg0.conf <<EOF
126111
127-
# $user
112+
# $user - added on $(date '+%Y-%m-%d %H:%M:%S')
128113
[Peer]
129114
PublicKey = $pub_key
130115
PresharedKey = $psk
@@ -136,8 +121,8 @@ log_info "Creating client configuration..."
136121
cat > "$client_config" <<EOF
137122
[Interface]
138123
PrivateKey = $priv_key
139-
Address = 10.88.88.$ip_suffix/24
140-
DNS = 1.1.1.1,8.8.8.8
124+
Address = ${client_ip%/*}/24
125+
DNS = 1.1.1.1,8.8.8.8,9.9.9.9
141126
142127
[Peer]
143128
PublicKey = $server_pubkey
@@ -149,31 +134,31 @@ EOF
149134

150135
chmod 600 "$client_config"
151136

152-
# ---------- Apply Config ----------
137+
# ---------- Apply Config (Safe Reload) ----------
153138
log_info "Applying configuration changes..."
154-
if wg syncconf wg0 <(wg-quick strip wg0 2>/dev/null); then
139+
if wg-quick strip wg0 >/tmp/wg-temp.conf 2>/dev/null && wg syncconf wg0 /tmp/wg-temp.conf; then
155140
log_success "Configuration applied successfully (live reload)"
156141
else
157-
log_warn "Live reload failed, restarting service..."
142+
log_warn "Live reload failed restarting service..."
158143
if ! systemctl restart wg-quick@wg0; then
159-
log_error "Failed to restart WireGuard service. Restoring backup..."
144+
log_error "Failed to restart WireGuard. Restoring backup..."
160145
cp "$config_backup" /etc/wireguard/wg0.conf
161146
rm -f "$client_config"
162147
exit 1
163148
fi
164149
fi
165150

166-
# ---------- Verify Installation ----------
151+
# ---------- Verify ----------
167152
if wg show wg0 | grep -q "$pub_key"; then
168-
log_success "Peer verified in running configuration"
153+
log_success "Peer verified in running configuration."
169154
else
170-
log_warn "Peer not found in running configuration but config file was updated"
155+
log_warn "Peer not detected live, but config updated successfully."
171156
fi
172157

173158
# ---------- Output ----------
174159
echo
175160
echo -e "${green}=========================================${nc}"
176-
log_success "WireGuard user '$user' has been created successfully!"
161+
log_success "WireGuard user '$user' created successfully!"
177162
echo "👤 Username : $user"
178163
echo "📍 Client IP : $client_ip"
179164
echo "🌍 Endpoint : $server_ip:$server_port"
@@ -188,24 +173,29 @@ if command -v qrencode >/dev/null 2>&1; then
188173
echo
189174
fi
190175

191-
# ---------- Display Config Content ----------
192-
echo -e "${yellow}📄 Client config content:${nc}"
176+
# ---------- Display Config ----------
177+
echo -e "${yellow}📄 Client configuration content:${nc}"
193178
cat "$client_config"
194179
echo
195180

196-
# ---------- Save Log ----------
181+
# ---------- Log Creation ----------
197182
mkdir -p /var/log/wireguard
183+
chmod 700 /var/log/wireguard
198184
{
199185
echo "[$(date '+%Y-%m-%d %H:%M:%S')] Created: $user ($client_ip)"
200186
echo "PublicKey: $pub_key"
201187
echo "Endpoint: $server_ip:$server_port"
202188
echo "---"
203189
} >> /var/log/wireguard/user-creation.log
190+
chmod 600 /var/log/wireguard/user-creation.log
204191

205-
# ---------- Final Instructions ----------
192+
# ---------- Final Notes ----------
206193
log_info "To revoke this user, run: wg-del $user"
207194
log_info "To show all users, run: wg-show"
208195

209-
read -n 1 -s -r -p "Press any key to return to menu..."
210-
clear
211-
m-wg
196+
# ---------- Return to Menu ----------
197+
if command -v m-wg >/dev/null 2>&1; then
198+
read -n 1 -s -r -p "Press any key to return to menu..."
199+
clear
200+
m-wg
201+
fi

0 commit comments

Comments
 (0)