-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathinit-firewall.sh
More file actions
430 lines (382 loc) · 14.1 KB
/
init-firewall.sh
File metadata and controls
430 lines (382 loc) · 14.1 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
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/bin/bash
set -euo pipefail # Exit on error, undefined vars, and pipeline failures
IFS=$'\n\t' # Stricter word splitting
# State file to track if firewall has been configured
STATE_FILE="/var/lib/firewall-configured"
# Disable IPv6 to prevent bypass of IPv4-only firewall rules
echo "Disabling IPv6..."
sysctl -w net.ipv6.conf.all.disable_ipv6=1 >/dev/null 2>&1 || true
sysctl -w net.ipv6.conf.default.disable_ipv6=1 >/dev/null 2>&1 || true
sysctl -w net.ipv6.conf.lo.disable_ipv6=1 >/dev/null 2>&1 || true
# Check if firewall is already configured
if [ -f "$STATE_FILE" ]; then
echo "Firewall already configured (found $STATE_FILE), skipping..."
echo "To reconfigure, delete $STATE_FILE and restart container"
exit 0
fi
echo "Starting firewall configuration..."
# Initialize DNS resolution statistics
TOTAL_DOMAINS=0
RESOLVED_DOMAINS=0
FAILED_DOMAINS=0
# 1. Extract Docker DNS info BEFORE any flushing
DOCKER_DNS_RULES=$(iptables-save -t nat | grep "127\.0\.0\.11" || true)
# 2. Get all Docker network interfaces BEFORE flushing (we'll need these later)
echo "Detecting Docker networks..."
DOCKER_NETWORKS=$(ip -o -f inet addr show | grep -v "127.0.0.1" | awk '{print $4}')
if [ -z "$DOCKER_NETWORKS" ]; then
echo "ERROR: Failed to detect any Docker networks"
exit 1
fi
# 3. Create ipset with CIDR support (do this BEFORE flushing so we can use network)
ipset destroy allowed-domains 2>/dev/null || true
ipset create allowed-domains hash:net
# Fetch GitHub meta information and aggregate + add their IP ranges
echo "Fetching GitHub IP ranges..."
gh_ranges=$(curl -s https://api.github.com/meta)
if [ -z "$gh_ranges" ]; then
echo "ERROR: Failed to fetch GitHub IP ranges"
exit 1
fi
if ! echo "$gh_ranges" | jq -e '.web and .api and .git' >/dev/null; then
echo "ERROR: GitHub API response missing required fields"
exit 1
fi
echo "Processing GitHub IPs..."
while read -r cidr; do
if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then
echo "ERROR: Invalid CIDR range from GitHub meta: $cidr"
exit 1
fi
echo "Adding GitHub range $cidr"
ipset add allowed-domains "$cidr" -exist
done < <(echo "$gh_ranges" | jq -r '(.web + .api + .git)[]' | aggregate -q)
# Add Anthropic IP ranges (official published ranges from https://docs.claude.com/en/api/ip-addresses)
echo "Adding Anthropic IP ranges..."
echo "Adding Anthropic CIDR range 160.79.104.0/23"
ipset add allowed-domains "160.79.104.0/23" -exist
# Add Anthropic specific IP addresses
for ip in \
"34.162.46.92" \
"34.162.102.82" \
"34.162.136.91" \
"34.162.142.92" \
"34.162.183.95"; do
echo "Adding Anthropic IP $ip"
ipset add allowed-domains "$ip" -exist
done
# Fetch and add Google Cloud/API IP ranges
echo "Fetching Google Cloud/API IP ranges..."
goog_ranges=$(curl -s https://www.gstatic.com/ipranges/goog.json)
if [ -z "$goog_ranges" ]; then
echo "ERROR: Failed to fetch Google IP ranges"
exit 1
fi
if ! echo "$goog_ranges" | jq -e '.prefixes' >/dev/null; then
echo "ERROR: Google API response missing required fields"
exit 1
fi
echo "Processing Google IPs..."
while read -r cidr; do
if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then
echo "ERROR: Invalid CIDR range from Google: $cidr"
exit 1
fi
echo "Adding Google range $cidr"
ipset add allowed-domains "$cidr" -exist
done < <(echo "$goog_ranges" | jq -r '.prefixes[].ipv4Prefix | select(. != null)')
# Fetch and add Cloudflare CDN IP ranges
echo "Fetching Cloudflare CDN IP ranges..."
cf_ranges=$(curl -s https://api.cloudflare.com/client/v4/ips)
if [ -z "$cf_ranges" ]; then
echo "ERROR: Failed to fetch Cloudflare IP ranges"
exit 1
fi
if ! echo "$cf_ranges" | jq -e '.result.ipv4_cidrs' >/dev/null; then
echo "ERROR: Cloudflare API response missing required fields"
exit 1
fi
echo "Processing Cloudflare IPs..."
while read -r cidr; do
if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then
echo "ERROR: Invalid CIDR range from Cloudflare: $cidr"
exit 1
fi
echo "Adding Cloudflare range $cidr"
ipset add allowed-domains "$cidr" -exist
done < <(echo "$cf_ranges" | jq -r '.result.ipv4_cidrs[]')
# Fetch and add AWS IP ranges (covers many AI services: Hugging Face, Replicate, etc.)
# Filtered for US East/West regions and EC2/CloudFront services only to limit allowlist size
echo "Fetching AWS IP ranges..."
aws_ranges=$(curl -s https://ip-ranges.amazonaws.com/ip-ranges.json)
if [ -z "$aws_ranges" ]; then
echo "ERROR: Failed to fetch AWS IP ranges"
exit 1
fi
if ! echo "$aws_ranges" | jq -e '.prefixes' >/dev/null; then
echo "ERROR: AWS API response missing required fields"
exit 1
fi
echo "Processing AWS IPs (US regions: us-east-1, us-west-2; Services: EC2, CLOUDFRONT)..."
while read -r cidr; do
if [[ ! "$cidr" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}/[0-9]{1,2}$ ]]; then
echo "ERROR: Invalid CIDR range from AWS: $cidr"
exit 1
fi
echo "Adding AWS range $cidr"
ipset add allowed-domains "$cidr" -exist
done < <(echo "$aws_ranges" | jq -r '.prefixes[] | select(.region == "us-east-1" or .region == "us-west-2") | select(.service == "EC2" or .service == "CLOUDFRONT") | .ip_prefix' | aggregate -q)
# Resolve and add other allowed domains (defense-in-depth: includes DNS backup for services above)
for domain in \
"dns.google" \
"1.1.1.1" \
"8.8.8.8" \
"8.8.4.4" \
"auth.openai.com" \
"chatgpt.com" \
"context7.com" \
"unpkg.com" \
"cdn.jsdelivr.net" \
"opencode.ai" \
"cdnjs.cloudflare.com" \
"github.com" \
"api.github.com" \
"raw.githubusercontent.com" \
"github.githubassets.com" \
"collector.github.com" \
"ghcr.io" \
"pkg-containers.githubusercontent.com" \
"nodejs.org" \
"registry.npmjs.org" \
"pypi.org" \
"files.pythonhosted.org" \
"astral.sh" \
"bun.sh" \
"crates.io" \
"static.crates.io" \
"index.crates.io" \
"docker.io" \
"registry-1.docker.io" \
"auth.docker.io" \
"production.cloudflare.docker.com" \
"api.anthropic.com" \
"docs.claude.com" \
"api.openai.com" \
"aistudio.google.com" \
"accounts.google.com" \
"oauth2.googleapis.com" \
"www.googleapis.com" \
"storage.googleapis.com" \
"content.googleapis.com" \
"generativelanguage.googleapis.com" \
"sentry.io" \
"statsig.anthropic.com" \
"statsig.com" \
"marketplace.visualstudio.com" \
"vscode.blob.core.windows.net" \
"update.code.visualstudio.com" \
"docs.mcp.cloudflare.com" \
"mcp.context7.com" \
"vercel.com" \
"ui.shadcn.com" \
"tailwindcss.com" \
"radix-ui.com" \
"fonts.googleapis.com" \
"fonts.gstatic.com" \
"react.dev" \
"reactjs.org" \
"esm.sh" \
"deb.debian.org" \
"security.debian.org" \
"archive.ubuntu.com" \
"security.ubuntu.com" \
"lucide.dev" \
"openrouter.ai" \
"api.cerebras.ai" \
"inference.cerebras.ai" \
"cloud.cerebras.ai" \
"cerebras.ai" \
"dashscope.aliyuncs.com" \
"qwen.ai" \
"qwenlm.ai" \
"aliyuncs.com" \
"alibabacloud.com" \
"cn-hangzhou.aliyuncs.com" \
"us-west-1.aliyuncs.com" \
"ap-southeast-1.aliyuncs.com" \
"api.minimax.chat" \
"minimax.chat" \
"z.ai" \
"api.cohere.ai" \
"cohere.ai" \
"api.together.xyz" \
"together.xyz" \
"api.replicate.com" \
"replicate.com" \
"api-inference.huggingface.co" \
"huggingface.co" \
"api.perplexity.ai" \
"perplexity.ai" \
"api.mistral.ai" \
"mistral.ai" \
"api.deepinfra.com" \
"deepinfra.com" \
"api.fireworks.ai" \
"fireworks.ai" \
"api.groq.com" \
"groq.com" \
"api.lepton.ai" \
"lepton.ai" \
"mancer.tech" \
"api.mancer.tech" \
"api.deepseek.com" \
"deepseek.com" \
"api.lingyiwanwu.com" \
"platform.lingyiwanwu.com"; do
# Check if this is already an IP address
if [[ "$domain" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "Adding IP address $domain"
ipset add allowed-domains "$domain" -exist
continue
fi
# Otherwise, resolve the hostname
TOTAL_DOMAINS=$((TOTAL_DOMAINS + 1))
echo "Resolving $domain..."
ips=$(dig +noall +answer A "$domain" | awk '$4 == "A" {print $5}')
if [ -z "$ips" ]; then
echo "WARNING: Failed to resolve $domain (continuing...)"
FAILED_DOMAINS=$((FAILED_DOMAINS + 1))
continue
fi
# Successfully resolved, add IPs to allowlist
domain_resolved=false
while read -r ip; do
if [[ ! "$ip" =~ ^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$ ]]; then
echo "WARNING: Invalid IP from DNS for $domain: $ip (skipping)"
continue
fi
echo "Adding $ip for $domain"
ipset add allowed-domains "$ip" -exist
domain_resolved=true
done < <(echo "$ips")
# Count as resolved only if at least one valid IP was added
if [ "$domain_resolved" = true ]; then
RESOLVED_DOMAINS=$((RESOLVED_DOMAINS + 1))
else
FAILED_DOMAINS=$((FAILED_DOMAINS + 1))
fi
done
echo ""
echo "IP allowlist built successfully"
echo "DNS Resolution Summary: ${RESOLVED_DOMAINS}/${TOTAL_DOMAINS} domains resolved successfully"
if [ "$FAILED_DOMAINS" -gt 0 ]; then
echo " WARNING: ${FAILED_DOMAINS} domains failed to resolve"
fi
echo ""
# 4. Now flush iptables and rebuild with our allowlist
echo "Flushing existing iptables rules..."
iptables -F
iptables -X
iptables -t nat -F
iptables -t nat -X
iptables -t mangle -F
iptables -t mangle -X
# 5. Restore Docker DNS NAT rules
if [ -n "$DOCKER_DNS_RULES" ]; then
echo "Restoring Docker DNS rules..."
iptables -t nat -N DOCKER_OUTPUT 2>/dev/null || true
iptables -t nat -N DOCKER_POSTROUTING 2>/dev/null || true
echo "$DOCKER_DNS_RULES" | xargs -L 1 iptables -t nat
fi
# 6. Allow DNS and localhost before setting restrictive policies
echo "Configuring base rules..."
# Allow outbound DNS
iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
# Allow inbound DNS responses
iptables -A INPUT -p udp --sport 53 -j ACCEPT
# Allow outbound SSH
iptables -A OUTPUT -p tcp --dport 22 -j ACCEPT
# Allow inbound SSH responses
iptables -A INPUT -p tcp --sport 22 -m state --state ESTABLISHED -j ACCEPT
# Allow localhost
iptables -A INPUT -i lo -j ACCEPT
iptables -A OUTPUT -o lo -j ACCEPT
# 7. Allow traffic to/from all Docker networks (for OTel, inter-container communication, etc.)
echo "Allowing Docker networks..."
while read -r network; do
echo " Allowing Docker network: $network"
iptables -A INPUT -s "$network" -j ACCEPT
iptables -A OUTPUT -d "$network" -j ACCEPT
done < <(echo "$DOCKER_NETWORKS")
# 8. Set default policies to DROP
echo "Setting restrictive default policies..."
iptables -P INPUT DROP
iptables -P FORWARD DROP
iptables -P OUTPUT DROP
# 9. Allow established connections for already approved traffic
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
# 10. Allow only specific outbound traffic to allowed domains
iptables -A OUTPUT -m set --match-set allowed-domains dst -j ACCEPT
# 11. Explicitly REJECT all other outbound traffic for immediate feedback
iptables -A OUTPUT -j REJECT --reject-with icmp-admin-prohibited
# 12. Configure IPv6 firewall rules (defense-in-depth if IPv6 couldn't be disabled)
echo "Configuring IPv6 firewall rules..."
# Set default policies to DROP for IPv6
ip6tables -P INPUT DROP 2>/dev/null || echo " Note: IPv6 may already be disabled"
ip6tables -P FORWARD DROP 2>/dev/null || true
ip6tables -P OUTPUT DROP 2>/dev/null || true
# Allow IPv6 localhost only
ip6tables -A INPUT -i lo -j ACCEPT 2>/dev/null || true
ip6tables -A OUTPUT -o lo -j ACCEPT 2>/dev/null || true
# Allow established IPv6 connections (for localhost)
ip6tables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT 2>/dev/null || true
ip6tables -A OUTPUT -m state --state ESTABLISHED,RELATED -j ACCEPT 2>/dev/null || true
# Explicitly REJECT all other IPv6 traffic
ip6tables -A INPUT -j REJECT 2>/dev/null || true
ip6tables -A OUTPUT -j REJECT 2>/dev/null || true
echo "IPv6 firewall rules configured"
echo ""
echo "Firewall configuration complete!"
echo ""
echo "Verifying firewall rules..."
# Verify IPv6 is disabled (warning only, not fatal)
if sysctl net.ipv6.conf.all.disable_ipv6 | grep -q "= 1"; then
echo "✓ Firewall verification passed - IPv6 is disabled"
else
echo "⚠ WARNING: IPv6 is still enabled (container restrictions may prevent disabling)"
echo " IPv6 traffic will be blocked by ip6tables rules as a security fallback"
echo " This is expected in some Docker environments and does not affect security"
fi
# Verify blocked domains
if curl --connect-timeout 5 https://example.com >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - was able to reach https://example.com"
exit 1
else
echo "Firewall verification passed - unable to reach https://example.com as expected"
fi
# Verify GitHub API access
if ! curl --connect-timeout 5 https://api.github.com/zen >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - unable to reach https://api.github.com"
exit 1
else
echo "Firewall verification passed - able to reach https://api.github.com as expected"
fi
# Verify OpenRouter API access
if ! curl --connect-timeout 5 https://openrouter.ai/api/v1/models >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - unable to reach https://openrouter.ai"
exit 1
else
echo "Firewall verification passed - able to reach https://openrouter.ai as expected"
fi
# Verify Cerebras API access
if ! curl --connect-timeout 5 https://api.cerebras.ai/v1/models >/dev/null 2>&1; then
echo "ERROR: Firewall verification failed - unable to reach https://api.cerebras.ai"
exit 1
else
echo "Firewall verification passed - able to reach https://api.cerebras.ai as expected"
fi
# Create state file to mark firewall as configured
echo "Creating state file $STATE_FILE..."
touch "$STATE_FILE"
echo "Firewall state saved - will skip configuration on subsequent container starts"