-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnic_sharing.sh
More file actions
executable file
·412 lines (362 loc) · 13.8 KB
/
Copy pathnic_sharing.sh
File metadata and controls
executable file
·412 lines (362 loc) · 13.8 KB
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
#!/bin/bash
# nic_sharing.sh — Share an internet connection via a Wi-Fi access point.
#
# Usage:
# sudo ./nic_sharing.sh on <src_iface> <wifi_iface> --ssid <SSID> --pass <PASS> [options]
# sudo ./nic_sharing.sh off <src_iface> <wifi_iface>
#
# Options (on only):
# --ssid <SSID> Wi-Fi network name (required)
# --pass <PASSWORD> WPA2 passphrase, 8–63 chars (required)
# --band <2.4|5> Radio band (default: 2.4)
# --channel <N> Wi-Fi channel (default: 6 for 2.4 GHz, 36 for 5 GHz)
# --dns <IP> DNS server pushed to clients via DHCP
# --domain <DOMAIN> Search domain pushed to clients via DHCP
#
# Requirements: hostapd, dnsmasq (with conf-dir=/etc/dnsmasq.d/ enabled),
# iw, ip, iptables, rfkill, nmcli
set -euo pipefail
# ---------------------------------------------------------------------------
# Runtime paths
# ---------------------------------------------------------------------------
readonly DNSMASQ_DROPIN="/etc/dnsmasq.d/nic-sharing.conf"
readonly HOSTAPD_CONF="/etc/hostapd/nic-sharing.conf"
readonly HOSTAPD_PID="/run/nic-sharing-hostapd.pid"
readonly STATE_FILE="/run/nic-sharing.state"
readonly GW_IP="192.168.60.1"
readonly DHCP_START="192.168.60.10"
readonly DHCP_END="192.168.60.50"
readonly DHCP_LEASE="12h"
# ---------------------------------------------------------------------------
# Argument parsing
# ---------------------------------------------------------------------------
usage() {
cat >&2 <<EOF
Usage: sudo $0 <on|off> <src_iface> <wifi_iface> [options]
on Enable sharing. Requires --ssid and --pass.
off Disable sharing and restore previous state.
Options (on only):
--ssid <SSID> Wi-Fi network name (required)
--pass <PASSWORD> WPA2 passphrase, 8–63 chars (required)
--band <2.4|5> Radio band: 2.4 GHz or 5 GHz (default: 2.4)
--channel <N> Wi-Fi channel (default: 6 for 2.4, 36 for 5 GHz)
--dns <IP> DNS server advertised to clients via DHCP
--domain <DOMAIN> Search domain advertised to clients via DHCP
EOF
exit 1
}
[[ "$#" -lt 3 ]] && usage
[[ "$1" != "on" && "$1" != "off" ]] && usage
ACTION="$1"
INTERNET_IFACE="$2"
WIFI_IFACE="$3"
# Option defaults
SSID=""
PASSWORD=""
BAND="2.4"
CHANNEL=""
DNS_SERVER=""
SEARCH_DOMAIN=""
shift 3
while [[ $# -gt 0 ]]; do
case "$1" in
--ssid) SSID="$2"; shift 2 ;;
--pass) PASSWORD="$2"; shift 2 ;;
--band) BAND="$2"; shift 2 ;;
--channel) CHANNEL="$2"; shift 2 ;;
--dns) DNS_SERVER="$2"; shift 2 ;;
--domain) SEARCH_DOMAIN="$2"; shift 2 ;;
*) echo "Error: unknown option: $1" >&2; usage ;;
esac
done
# ---------------------------------------------------------------------------
# Guards
# ---------------------------------------------------------------------------
require_root() {
if [[ "$EUID" -ne 0 ]]; then
echo "Error: this script must be run as root (use sudo)." >&2
exit 1
fi
}
check_deps() {
local missing=()
for cmd in hostapd dnsmasq iw ip iptables rfkill nmcli sysctl; do
command -v "$cmd" &>/dev/null || missing+=("$cmd")
done
if [[ "${#missing[@]}" -gt 0 ]]; then
echo "Error: missing required tools: ${missing[*]}" >&2
echo " apt install dnsmasq hostapd rfkill network-manager iproute2 iptables" >&2
exit 1
fi
}
check_dnsmasq_dropin() {
# dnsmasq must be configured to read /etc/dnsmasq.d/ drop-ins.
# On Debian/Ubuntu this is enabled by default. On other distros you may
# need to add: conf-dir=/etc/dnsmasq.d/,*.conf to /etc/dnsmasq.conf.
if ! grep -rqE '^\s*conf-dir\s*=\s*/etc/dnsmasq\.d' /etc/dnsmasq.conf 2>/dev/null; then
echo "Warning: /etc/dnsmasq.conf does not appear to include /etc/dnsmasq.d/." >&2
echo " Add 'conf-dir=/etc/dnsmasq.d/,*.conf' to /etc/dnsmasq.conf if sharing does not work." >&2
fi
}
validate_wifi_iface() {
if [[ ! -d "/sys/class/net/$WIFI_IFACE" ]]; then
echo "Error: interface '$WIFI_IFACE' does not exist." >&2
exit 1
fi
if ! iw dev "$WIFI_IFACE" info &>/dev/null; then
echo "Error: '$WIFI_IFACE' is not a Wi-Fi interface." >&2
exit 1
fi
}
validate_on_args() {
if [[ -z "$SSID" || -z "$PASSWORD" ]]; then
echo "Error: --ssid and --pass are required." >&2
exit 1
fi
if [[ "${#PASSWORD}" -lt 8 || "${#PASSWORD}" -gt 63 ]]; then
echo "Error: password must be 8–63 characters (WPA2 requirement)." >&2
exit 1
fi
if [[ "$BAND" != "2.4" && "$BAND" != "5" ]]; then
echo "Error: --band must be '2.4' or '5'." >&2
exit 1
fi
# Derive default channel from band if not explicitly set
if [[ -z "$CHANNEL" ]]; then
[[ "$BAND" == "5" ]] && CHANNEL=36 || CHANNEL=6
fi
}
# ---------------------------------------------------------------------------
# State file — persists across on/off calls (survives the gap between them)
# ---------------------------------------------------------------------------
state_set() { echo "${1}=${2}" >> "$STATE_FILE"; }
state_get() {
[[ -f "$STATE_FILE" ]] && grep -m1 "^${1}=" "$STATE_FILE" | cut -d= -f2- || echo ""
}
state_clear() { rm -f "$STATE_FILE"; }
# ---------------------------------------------------------------------------
# Wi-Fi interface management
# ---------------------------------------------------------------------------
disconnect_wifi_if_needed() {
local state
state=$(nmcli -t -f GENERAL.STATE dev show "$WIFI_IFACE" 2>/dev/null \
| grep -o '[0-9]*' | head -1 || echo "0")
if [[ "$state" -eq 100 ]]; then
echo "Wi-Fi interface $WIFI_IFACE is connected — disconnecting..."
nmcli dev disconnect "$WIFI_IFACE"
state_set "wifi_was_connected" "1"
else
state_set "wifi_was_connected" "0"
fi
}
restore_wifi_if_needed() {
if [[ "$(state_get wifi_was_connected)" == "1" ]]; then
echo "Restoring previous Wi-Fi connection on $WIFI_IFACE..."
nmcli dev connect "$WIFI_IFACE" || true
fi
}
unblock_wifi() {
if rfkill list wifi 2>/dev/null | grep -q "Soft blocked: yes"; then
rfkill unblock wifi
echo "Wi-Fi unblocked."
fi
}
# ---------------------------------------------------------------------------
# ip_forward — preserve prior value, do not blindly set to 0 on off
# ---------------------------------------------------------------------------
enable_ip_forward() {
local current
current=$(sysctl -n net.ipv4.ip_forward)
state_set "ip_forward_was" "$current"
sysctl -q -w net.ipv4.ip_forward=1
echo "IP forwarding enabled."
}
restore_ip_forward() {
local was
was=$(state_get "ip_forward_was")
local target="${was:-0}"
sysctl -q -w "net.ipv4.ip_forward=${target}"
echo "IP forwarding restored to ${target}."
}
# ---------------------------------------------------------------------------
# iptables rules
# ---------------------------------------------------------------------------
add_nat_rules() {
if ! iptables -t nat -C POSTROUTING -o "$INTERNET_IFACE" -j MASQUERADE 2>/dev/null; then
iptables -t nat -A POSTROUTING -o "$INTERNET_IFACE" -j MASQUERADE
echo "NAT MASQUERADE rule added."
else
echo "NAT MASQUERADE rule already present."
fi
if ! iptables -C FORWARD -i "$INTERNET_IFACE" -o "$WIFI_IFACE" \
-m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null; then
iptables -A FORWARD -i "$INTERNET_IFACE" -o "$WIFI_IFACE" \
-m state --state RELATED,ESTABLISHED -j ACCEPT
echo "FORWARD rule (RELATED,ESTABLISHED) added."
fi
if ! iptables -C FORWARD -i "$WIFI_IFACE" -o "$INTERNET_IFACE" -j ACCEPT 2>/dev/null; then
iptables -A FORWARD -i "$WIFI_IFACE" -o "$INTERNET_IFACE" -j ACCEPT
echo "FORWARD rule (outgoing) added."
fi
}
remove_nat_rules() {
iptables -t nat -D POSTROUTING -o "$INTERNET_IFACE" -j MASQUERADE 2>/dev/null \
&& echo "NAT MASQUERADE rule removed." || true
iptables -D FORWARD -i "$INTERNET_IFACE" -o "$WIFI_IFACE" \
-m state --state RELATED,ESTABLISHED -j ACCEPT 2>/dev/null \
&& echo "FORWARD rule (RELATED,ESTABLISHED) removed." || true
iptables -D FORWARD -i "$WIFI_IFACE" -o "$INTERNET_IFACE" -j ACCEPT 2>/dev/null \
&& echo "FORWARD rule (outgoing) removed." || true
}
# ---------------------------------------------------------------------------
# dnsmasq — drop-in file, never touches /etc/dnsmasq.conf
# ---------------------------------------------------------------------------
write_dnsmasq_conf() {
mkdir -p "$(dirname "$DNSMASQ_DROPIN")"
{
echo "# Generated by nic_sharing.sh — do not edit manually."
echo "interface=${WIFI_IFACE}"
echo "dhcp-range=${DHCP_START},${DHCP_END},${DHCP_LEASE}"
echo "dhcp-option=3,${GW_IP}" # default gateway
if [[ -n "$DNS_SERVER" ]]; then
echo "dhcp-option=6,${DNS_SERVER}"
fi
if [[ -n "$SEARCH_DOMAIN" ]]; then
echo "domain=${SEARCH_DOMAIN}"
echo "dhcp-option=15,${SEARCH_DOMAIN}"
echo "dhcp-option=option:domain-search,${SEARCH_DOMAIN}"
if [[ -n "$DNS_SERVER" ]]; then
# Forward domain queries to the specified DNS server
echo "server=/${SEARCH_DOMAIN}/${DNS_SERVER}"
fi
fi
} > "$DNSMASQ_DROPIN"
echo "dnsmasq drop-in written: $DNSMASQ_DROPIN"
}
remove_dnsmasq_conf() {
if [[ -f "$DNSMASQ_DROPIN" ]]; then
rm "$DNSMASQ_DROPIN"
echo "dnsmasq drop-in removed."
fi
}
# ---------------------------------------------------------------------------
# hostapd — explicit PID file, options before config file
# ---------------------------------------------------------------------------
write_hostapd_conf() {
local hw_mode
[[ "$BAND" == "5" ]] && hw_mode="a" || hw_mode="g"
mkdir -p "$(dirname "$HOSTAPD_CONF")"
{
echo "# Generated by nic_sharing.sh — do not edit manually."
echo "interface=${WIFI_IFACE}"
echo "driver=nl80211"
echo "ssid=${SSID}"
echo "hw_mode=${hw_mode}"
echo "channel=${CHANNEL}"
echo "macaddr_acl=0"
echo "auth_algs=1"
echo "ignore_broadcast_ssid=0"
echo "wpa=2"
echo "wpa_passphrase=${PASSWORD}"
echo "wpa_key_mgmt=WPA-PSK"
echo "rsn_pairwise=CCMP"
echo "ieee80211n=1"
echo "wmm_enabled=1"
if [[ "$BAND" == "5" ]]; then
echo "ieee80211ac=1"
fi
} > "$HOSTAPD_CONF"
echo "hostapd configuration written (SSID: ${SSID}, band: ${BAND} GHz, channel: ${CHANNEL})."
}
start_hostapd() {
# -B: run in background; -P: write PID file; config file must come last
hostapd -B -P "$HOSTAPD_PID" "$HOSTAPD_CONF"
echo "hostapd started (PID: $(cat "$HOSTAPD_PID"))."
}
stop_hostapd() {
if [[ -f "$HOSTAPD_PID" ]]; then
local pid
pid=$(cat "$HOSTAPD_PID")
if kill -0 "$pid" 2>/dev/null; then
kill "$pid"
echo "hostapd stopped (PID: ${pid})."
else
echo "hostapd PID ${pid} not running."
fi
rm -f "$HOSTAPD_PID"
else
# Fallback for stale state (e.g. after a crash)
pkill -x hostapd 2>/dev/null && echo "hostapd stopped (pkill fallback)." || true
fi
rm -f "$HOSTAPD_CONF"
}
# ---------------------------------------------------------------------------
# ERR trap — rolls back partial setup if enable_sharing fails mid-way
# ---------------------------------------------------------------------------
_ROLLBACK=false
_rollback_on_error() {
[[ "$_ROLLBACK" != true ]] && return
echo "Error during setup — rolling back..." >&2
stop_hostapd || true
remove_dnsmasq_conf || true
systemctl restart dnsmasq || true
ip addr flush dev "$WIFI_IFACE" 2>/dev/null || true
ip link set "$WIFI_IFACE" down 2>/dev/null || true
remove_nat_rules || true
restore_ip_forward || true
restore_wifi_if_needed || true
state_clear || true
}
trap '_rollback_on_error' ERR
# ---------------------------------------------------------------------------
# Main actions
# ---------------------------------------------------------------------------
enable_sharing() {
_ROLLBACK=true
echo "==> Enabling sharing: ${INTERNET_IFACE} → ${WIFI_IFACE}"
unblock_wifi
disconnect_wifi_if_needed
enable_ip_forward
add_nat_rules
ip addr add "${GW_IP}/24" dev "$WIFI_IFACE" 2>/dev/null || true
ip link set "$WIFI_IFACE" up
echo "Interface ${WIFI_IFACE} up at ${GW_IP}."
check_dnsmasq_dropin
write_dnsmasq_conf
systemctl restart dnsmasq
echo "dnsmasq restarted."
write_hostapd_conf
start_hostapd
_ROLLBACK=false
echo "==> Internet sharing enabled."
}
disable_sharing() {
echo "==> Disabling sharing: ${INTERNET_IFACE} → ${WIFI_IFACE}"
stop_hostapd || true
remove_dnsmasq_conf || true
systemctl restart dnsmasq || true
echo "dnsmasq restarted."
remove_nat_rules
restore_ip_forward
ip addr flush dev "$WIFI_IFACE" 2>/dev/null || true
ip link set "$WIFI_IFACE" down 2>/dev/null || true
echo "Interface ${WIFI_IFACE} down."
restore_wifi_if_needed
state_clear
echo "==> Internet sharing disabled."
}
# ---------------------------------------------------------------------------
# Entry point
# ---------------------------------------------------------------------------
require_root
check_deps
case "$ACTION" in
on)
validate_wifi_iface
validate_on_args
enable_sharing
;;
off)
disable_sharing
;;
esac