Firewalls: iptables/nftables, Security Groups, Network ACLs, Egress Control
"Packets are routed before the firewall rules can be applied, effectively ignoring your firewall configuration." — Docker documentation, Packet filtering and firewalls (on
docker run -pand ufw)
خلاصه (Summary): فایروال (Firewall) فهرستی از قاعدههاست که بستهبهبسته یا جریانبهجریان تصمیم میگیرد چه چیزی وارد یک ماشین یا شبکه شود، از آن خارج شود یا از آن عبور کند؛ همهٔ مهارت در این است که بدانید این فهرست کجا نشسته (میزبان، پل کانتینر، زیرشبکه، کارت شبکهٔ یک سرور ابری، Pod) و چه چیزی را میبیند (۵-تایی، وضعیت اتصال، اینترفیس).
تمرکز (Focus): آنچه فایروال روی آن فیلتر میکند، بیحالت (Stateless) در برابر حالتدار (Stateful)، رد پیشفرض (Default-deny)، hookها و tableهای netfilter، نحو iptables و nftables، conntrack، لاگ و محدودکردن نرخ، ICMP و PMTUD، IPv6، قاعدههای فایروال Docker، NetworkPolicy در Kubernetes، Security Group و Network ACL در AWS در مقایسه با GCP و Azure، کنترل خروجی (Egress)، bind کردن listener بهعنوان دیوار دوم و روش ممیزی (Audit) همهٔ اینها.
هدف یادگیری (Learning goal): هر مجموعهقاعدهای (iptables، nft، security group، NACL، NetworkPolicy) را بخوانید و بگویید کدام بسته را رد میکند و چرا؛ برای یک سرور، یک میزبان Docker و یک namespace سیاست default-deny بنویسید؛ و پنج شکست کلاسیک (پورتهای ephemeral، دور زدن Docker، سیاست اجرانشده، health check مسدود، ICMP مسدود) را بشناسید.
این فصل فیلتر کردن بسته است آنطور که یک برنامهنویس با آن روبهرو میشود: یک سرور لینوکسی که روی آن deploy میکنید، docker run -p، یک security group ابری، یک namespace در Kubernetes. روی مدلهای شبکه (بسته از چه ساخته شده)، آدرسدهی IP و CIDR (قاعدهها چه چیزی را match میکنند)، NAT و port forwarding (بازنویسیهایی که کنار فیلتر انجام میشود) و پورت، سوکت و اتصال (سوکت شنوا چیست، conntrack و پورتهای ephemeral چطور رفتار میکنند) بنا شده است. مدلهای شبکهٔ کانتینر در Docker networking و Kubernetes networking است؛ تونلهایی که جای پورت باز را میگیرند در VPN و تونل؛ نگاه عَرَضمحور (از نشانه به علت) در راهنمای عیبیابی. سمت حمله (DDoS، WAF، سیلابهای حجمی) فصل system-design به نام DDoS و امنیت شبکه است؛ معماری امنیت در security foundations، قاعدههای مبتنی بر هویت در authorization و zero trust و هویت سرویس در mTLS. این صفحه آنها را تکرار نمیکند.
نقشهٔ صفحه (Page map)
| اگر دنبال این هستید | بروید به |
|---|---|
| جدولهایی که باید حفظ کرد | همهچیز در یک دقیقه |
| چرا فایروال هست و سه بدفهمی | چرا فایروال وجود دارد |
| netfilter، iptables، nftables، security group: چه کسی چه چیزی ساخت | از کجا آمده |
| ۵-تایی، وضعیت، اینترفیس، جهت | فایروال روی چه چیزی فیلتر میکند |
| بیحالت و حالتدار | Stateless و Stateful |
| رد پیشفرض و allow-list | Default-deny |
| hookها، tableها، دیاگرام مسیر بسته | hookها و tableهای netfilter |
ESTABLISHED,RELATED، ct state، ابزار conntrack | conntrack و وضعیتها |
رمزگشایی -A INPUT -p tcp --dport 22 -m conntrack ... | نحو iptables |
nft list ruleset، set، map، inet، iptables-nft | nftables |
| ufw و firewalld | Front-endها |
log، limit rate، meter، fail2ban | لاگ و محدودکردن نرخ |
| چرا همهٔ ICMP را نبندیم، PMTUD، hex dump | ICMP |
| NAT نیست که پشتش پنهان شوید | فایروال IPv6 |
-p ufw را دور میزند، DOCKER-USER، Docker 28 به بعد | Docker و فایروال |
| پیشفرض allow، selectorها، پشتیبانی CNI، eBPF | Kubernetes NetworkPolicy |
| مقایسهٔ SG، NACL، GCP، Azure | فایروالهای ابری |
| نشت داده، زنجیرهٔ تأمین، NAT gateway، قاعدهٔ FQDN | کنترل Egress |
| فایروال میزبان در برابر محیط، bind به 127.0.0.1 | میزبان در برابر محیط، bind کردن listener |
| WAF در برابر فایروال در برابر security group | جدول لایهها |
| دیروز کار میکرد | شکستهای رایج |
شمارندهها، flow log، conntrack -L | ممیزی |
| ترتیب ارزیابی، verdictها، اولویتها | سازوکار |
| Go: بررسیگر سیاست، listener ادمین روی Unix socket | حل مسئلههای کلاسیک |
| Laravel: middleware بر پایهٔ CIDR، TrustProxies، webhook | Laravel |
| کدام کنترل برای کدام وضعیت | انتخاب |
| از مونولیت تا توزیعشده | در معماری |
| بازتولید روی ماشین خودتان | آزمایشگاه |
| بدفهمیها، چکیده، واژهنامه | بدفهمیها، چکیده، واژهنامه |
همهچیز در یک دقیقه (Everything in one minute)
قاعده به چه چیزی نگاه میکند. هر ردیف بعداً باز میشود.
| Match field | Example | Needs state? | Where it exists |
|---|---|---|---|
| Source / destination IP | ip saddr 10.0.0.0/8 | No | iptables, nft, SG, NACL, NetworkPolicy ipBlock |
| Protocol | tcp, udp, icmp, ipv6-icmp | No | everywhere |
| Source / destination port | tcp dport 22 | No | everywhere (not ICMP) |
| TCP flags | tcp flags syn | No | iptables, nft (not clouds) |
| Interface and direction | iifname "eth0", -i eth0, INPUT vs OUTPUT | No | hosts; clouds attach rules to an ENI, a subnet or a NIC |
| Connection state | ct state established,related | Yes | iptables -m conntrack, nft ct state, SG (implicit) |
| Labels instead of addresses | pod labels, SG references, tags, service tags | Depends | NetworkPolicy, SG, GCP tags, Azure ASG |
پنج جایی که فهرست قاعدهها میتواند باشد.
| Place | Product | Scope | Default for new traffic |
|---|---|---|---|
| The Linux host | iptables, nftables, ufw, firewalld | One machine, all interfaces | ACCEPT (until you set a policy) |
| The container bridge | Docker's own rules in DOCKER-* chains | Containers on this host | Published ports open to everyone |
| The cloud network interface | AWS security group, GCP firewall rule, Azure NSG | One instance (or a tagged set) | Inbound deny, outbound allow |
| The cloud subnet | AWS network ACL | Everything in a subnet | Default NACL allows all; a new custom one denies all |
| The pod | Kubernetes NetworkPolicy (enforced by the CNI) | Pods in a cluster | Allow all until a policy selects the pod |
پنج شکستی که باید انتظارش را داشت.
| Symptom | Usual cause | Chapter section |
|---|---|---|
| SG allows 443, clients still time out | NACL blocks the return traffic to ephemeral ports | Failures |
| ufw denies 5432, the database is public anyway | Docker published the port; the packet never reaches INPUT | Docker |
| NetworkPolicy applied, nothing changed | The CNI does not enforce NetworkPolicy | Kubernetes |
| Load balancer marks all targets unhealthy | Health-check source not allowed by SG or NACL | Failures |
| Small requests work, big uploads hang | ICMP "fragmentation needed" / "packet too big" is dropped | ICMP |
چرا فایروال وجود دارد (Why firewalls exist)
ماشینی که روی یک پورت گوش میدهد هر کسی را که به آن برسد میپذیرد. بیشتر سرویسها هرگز برای روبهرو شدن با کل اینترنت طراحی نشدهاند: یک پایگاهداده، یک Redis، یک پنل ادمین، sshd با ورود با رمز، یک endpoint متریک. فایروال ارزانترین جا برای گفتن «این پورت فقط برای این کلاینتهاست» است، چون برای همهٔ برنامههای روی ماشین کار میکند، از جمله آنهایی که کسی نصبشان را یادش نیست.
| Without a firewall | With one |
|---|---|
| Every listening socket is a public service | Only the ports you named are reachable |
| One misconfigured service (Redis without a password) is a breach | The same mistake is reachable only from the allowed range |
| A compromised process can talk to anything | Egress rules limit where it can send data or fetch tools |
| Scanning finds everything in minutes | Dropped packets give scanners nothing; logs show who tried |
تصویری از زندگی روزمره. ساختمانی با دربان. دربان نامههای شما را نمیخواند (آن کار برنامه است)؛ میبیند شما کی هستید (آدرس مبدأ)، از کدام در میآیید (پورت) و آیا کسی از داخل برایتان زنگ زده (وضعیت اتصال). دربان بیحالت یک فهرست برای ورود و یک فهرست برای خروج دارد و هر بار هر دو را چک میکند. دربان حالتدار یادش میماند «این مهمان دعوت شده بود» و پاسخ را بینگاه دوباره رد میکند.
سه بدفهمی، از همین ابتدا.
| Misunderstanding | Reality |
|---|---|
| "NAT hides my servers, so IPv6 needs no firewall" | NAT was never a security mechanism; RFC 4864 says so plainly. With IPv6 every host has a global address, so the firewall is the only wall |
| "My firewall denies the port, so the port is closed" | A firewall hides a port from the network; the process still listens. Another path (Docker's DNAT, a second interface, a pod network) can reach it |
| "Block ICMP, it is only ping" | ICMP carries the errors that make TCP work (fragmentation needed, destination unreachable). Blocking all of it creates MTU black holes |
از کجا آمده (Where it comes from)
| Source | What it gave us |
|---|---|
| ipfwadm, ipchains (Linux 1.x, 2.2) | The first Linux packet filters; rules in kernel lists |
| iptables / netfilter (Linux 2.4, 2001) | Hooks in the network stack, tables (filter, nat, mangle, raw), connection tracking and the -m match extensions |
| nftables (merged in Linux 3.13) | One rule engine and one tool nft replacing iptables, ip6tables, arptables, ebtables; sets, maps, the inet family |
| RFC 4864 (2007) | "Local Network Protection for IPv6": why NAT is not a firewall and what to do instead |
| RFC 4890 (2007) | "ICMPv6 Filtering Recommendations": which ICMPv6 messages must never be dropped |
| RFC 1191 / RFC 4821 | Path MTU Discovery for IPv4 and the "packetization layer" variant that survives dropped ICMP |
| AWS VPC security groups | The instance-level, stateful, allow-only model that every cloud copied in some form |
Kubernetes NetworkPolicy (networking.k8s.io/v1) | A label-based, additive allow model enforced by the network plugin |
| Cilium and eBPF | Policy enforced in eBPF programs in the kernel instead of long iptables lists |
خود پروژهٔ nftables هدفش را اعلام میکند: "nftables is the modern Linux kernel packet classification framework. New code should use it instead of the legacy {ip,ip6,arp,eb}_tables (xtables) infrastructure." همان صفحه میگوید iptables کجا لنگ بود: یک extension برای هر پروتکل، "Faster packet classification through enhanced generic set and map infrastructure" و "Simplified dual stack IPv4/IPv6 administration, through the new inet family".
فهرست مفاهیم (The concept catalogue)
فایروال روی چه چیزی فیلتر میکند: ۵-تایی (5-tuple)، وضعیت، اینترفیس و جهت حیاتی
به زبان ساده: قاعده یک پرسش دربارهٔ هدر بسته است («مبدأ در این بازه است و پورت مقصد ۲۲؟») بهاضافهٔ یک پاسخ («accept» یا «drop»). فایروال هدر را میخواند؛ HTTP، SQL یا کاربر را نمیفهمد.
بدفهمی رایج: «فایروال میتواند GET /health را اجازه دهد و POST /admin را نه.» فیلتر بسته (Packet filter) آدرسها، پورتها، پرچمها و وضعیت اتصال را میبیند. URL، متد و کوکی داخل payload (و داخل TLS) است؛ این کار پراکسی یا WAF است، جدول لایهها را ببینید.
تعریف: کلید کلاسیک ۵-تایی است: IP مبدأ، پورت مبدأ، IP مقصد، پورت مقصد، پروتکل. چهار ورودی دیگر در عمل مهماند: اینترفیسی که بسته از آن آمده یا به آن میرود، جهت نسبت به میزبان (به میزبان، از میزبان، یا از میان آن)، وضعیت اتصال (new، established، related، invalid) و markها و پرچمهای بسته. مستندات Azure همین مدل را برای قاعدههایش میگوید: "Security rules are evaluated and applied based on the five-tuple information of source, source port, destination, destination port, and protocol."
Ethernet | IPv4 header | TCP header | payload
| proto=6 src=172.19.0.3 dst=172.19.0.2 | sport=52386 dport=5432 flags=SYN |
^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
protocol source / destination IP source / destination port => the 5-tupleیک ضبط واقعی از بستهای که میزبانِ default-deny آن را drop کرد، با همهٔ بایتهایی که یک قاعده میتواند match کند. فریم از tcpdump -n -XX روی یک کانتینر لینوکسی آمده؛ offsetها از ابتدای فریم Ethernet است:
18:01:24.562436 IP 172.19.0.3.52386 > 172.19.0.2.5432: Flags [S], seq 1812388152, win 64240, length 0
0x0000: 3e20 ea32 077e 4660 4252 9bd4 0800 4500 >..2.~F`BR....E.
0x0010: 003c e465 4000 4006 fe2a ac13 0003 ac13 .<.e@.@..*......
0x0020: 0002 cca2 1538 6c06 d938 0000 0000 a002 .....8l..8......| Offset | Bytes | Field | Value | A rule that matches it |
|---|---|---|---|---|
| 0x00 | 3e20 ea32 077e / 4660 4252 9bd4 | dest MAC / source MAC | the two NICs | ether saddr (rarely used) |
| 0x0c | 0800 | EtherType | IPv4 | meta protocol ip |
| 0x0e | 45 | version 4, header length 5 words | 20-byte header | (implicit) |
| 0x16 | 40 / 06 | TTL 64 / protocol 6 | TCP | ip protocol tcp (-p tcp) |
| 0x1a | ac13 0003 | source IP | 172.19.0.3 | ip saddr 172.19.0.3 |
| 0x1e | ac13 0002 | destination IP | 172.19.0.2 | ip daddr 172.19.0.2 |
| 0x22 | cca2 | source port | 52386 (ephemeral) | tcp sport 52386 |
| 0x24 | 1538 | destination port | 5432 | tcp dport 5432 |
| 0x2f | 02 (in a002: header length 10 words, flags 02) | TCP flags | SYN only | tcp flags syn, ct state new |
سناریوهای واقعی: یک قاعدهٔ allow برای 10.0.0.0/8 روی پورت ۲۲؛ drop همهٔ SYNهای پورت ۵۴۳۲ از بیرون VPC؛ یک قاعدهٔ egress که فقط tcp dport 443 را به یک ارائهدهندهٔ پرداخت اجازه میدهد؛ یک security group که بهجای آدرس، نام security group دیگری را میآورد.
| Product | Fields it can match |
|---|---|
| iptables / nftables | Everything in the table above, plus marks, packet length, owner uid (-m owner), rate, hash, geo (extension) |
| AWS security group | Protocol, port range, ICMP type and code, source or destination as CIDR, prefix list or another SG |
| AWS network ACL | Protocol, port range, ICMP type and code, CIDR; numbered rules |
| GCP VPC firewall rule | Protocol and ports, source or destination ranges, source and target tags or service accounts, direction, priority |
| Azure NSG | The 5-tuple, service tags, application security groups, priority |
| Kubernetes NetworkPolicy | Pod and namespace labels, ipBlock CIDRs, protocol and port (TCP, UDP, SCTP) |
Stateless و Stateful (بیحالت و حالتدار) حیاتی
به زبان ساده: فیلتر بیحالت هر بسته را تنها قضاوت میکند؛ پس باید درخواست و جداگانه پاسخ را اجازه دهید. فیلتر حالتدار اتصال را یادش میماند: درخواست را اجازه دهید، پاسخ خودکار اجازه دارد.
بدفهمی رایج: «حالتدار یعنی فقط TCP را دنبال میکند.» conntrack لینوکس، security groupهای AWS و بقیه «جریان» UDP و ICMP را هم با timeout دنبال میکنند؛ برای UDP جریان یعنی «یک بسته رفت، پس بستهای از همان آدرس و پورت میتواند برگردد».
تعریف: فایروال حالتدار جدولی از جریانها (Flow) نگه میدارد. بستهٔ اول جریان با قاعدهها سنجیده میشود؛ اگر پذیرفته شد جریان ثبت میشود و بستههای بعدی همان جریان (هر دو جهت) با جدول match میشوند و از قاعدهها رد میشوند. فایروال بیحالت جدول ندارد؛ هر بسته دوباره با فهرست قاعدهها سنجیده میشود.
Stateful (Linux conntrack, AWS security group) Stateless (AWS network ACL)
1 client -> :443 SYN rule says allow, flow recorded rule IN 100 allows tcp 443
2 server -> client:51344 SYN,ACK matches the flow: allowed rule OUT needed for ephemeral 51344
3 client -> :443 ACK, data matches the flow: allowed rule IN 100 again
4 server -> client:51344 data matches the flow: allowed rule OUT againسناریوهای واقعی: وبسروری که با یک قاعدهٔ ورودی و بدون هیچ قاعدهٔ خروجی کار میکند (حالتدار)؛ زیرشبکهای که «443 را اجازه میدهد» ولی هر اتصال گیر میکند چون بازهٔ ephemeral خروجی نیست (بیحالت)؛ تغییر قاعدهای که نشست SSH در حال تایپ شما را نمیکُشد (حالتدار، چون اتصال از قبل ردیابی شده).
| Product | Stateful? | Detail |
|---|---|---|
| Linux netfilter | Only if you use conntrack (ct state) | Loaded by default when a rule needs it; you write ct state established,related accept yourself |
| AWS security group | Yes | "responses to inbound traffic are allowed to flow out of the instance regardless of outbound security group rules, and vice versa" |
| AWS network ACL | No | "responses to that traffic are not automatically allowed" |
| GCP VPC firewall | Yes (as designed) | See the cloud section for the sourcing note |
| Azure NSG | Yes | "Network security group rules only affect new connections" |
| Kubernetes NetworkPolicy | Yes | "Reply traffic for those allowed connections will also be implicitly allowed" |
راهحل / نحوهٔ استفاده: در nftables و iptables قاعدهٔ established را همیشه نزدیک بالا بگذارید (مسیر داغ است). در AWS تا وقتی deny در سطح زیرشبکه لازم نیست NACLها را روی پیشفرض بگذارید و وقتی لازم شد بازهٔ ephemeral برگشت را اضافه کنید.
Default-deny و allow-list (رد پیشفرض و فهرست مجاز) حیاتی
به زبان ساده: از «هیچ چیز مجاز نیست» شروع کنید، بعد آنچه مجاز است را فهرست کنید. عکسش (همهچیز را اجازه بده، بعد سعی کن چیزهای بد را فهرست کنی) تمام نمیشود.
بدفهمی رایج: «default deny روی INPUT کافی است.» Egress، FORWARD و شبکهٔ کانتینر هرکدام پیشفرض خودشان را دارند. میزبانی میتواند روی INPUT بینقص باشد و همچنان برای ترافیکی که forward میکند یک relay باز باشد، یا اسرار را به هر جایی بفرستد.
تعریف: policy یک chain همان verdict برای بستهای است که با هیچ قاعدهای match نشود. policy drop آن chain را به allow-list تبدیل میکند؛ هر قاعدهٔ accept استثنایی بر ردکردن است. ابرها این را در سمت ورودی security group و در NACLها (قاعدهٔ نهایی ضمنی «deny all» با شمارهٔ *) به شما میدهند.
Policy ACCEPT (the iptables/nft default) Policy DROP (an allow-list)
rule 1 drop tcp dport 23 rule 1 accept ct established,related
rule 2 drop tcp dport 3306 rule 2 accept tcp dport {80,443}
...(you forgot 6379) (policy) drop everything else, including 6379
6379 is open 6379 is closedسناریوهای واقعی: Redis که با package manager نصب شده و روی همهٔ اینترفیسها گوش میدهد؛ پورت دیباگی که یک ساعت باز شد و فراموش شد؛ سرویس جدیدی روی پورت جدید که کسی آن را به blocklist اضافه نکرد.
| Product | Default for new traffic |
|---|---|
| iptables, nftables (no ufw) | ACCEPT in every chain |
| ufw | "default incoming policy of deny, a default forward policy of deny, and a default outgoing policy of allow" (ufw man page, Ubuntu) |
| firewalld | Inter-zone traffic denied, intra-zone allowed by zone principles |
| AWS security group | No inbound rules (deny), one allow-all outbound rule |
| AWS default NACL | Allows all inbound and outbound; a new custom NACL denies all until you add rules |
| Azure NSG | Default rules at priorities 65000, 65001, 65500: allow VNet and load balancer inbound, deny the rest |
| Kubernetes | "if no policies exist in a namespace, then all ingress and egress traffic is allowed" |
راهحل / نحوهٔ استفاده: پیش از گذاشتن policy drop روی یک ماشین راهدور مطمئن شوید قاعدهٔ SSH خودتان از قبل هست (یا تغییر زمانبندیشده برمیگردد)، وگرنه خودتان را بیرون میاندازید. آزمایشگاه ترتیب را نشان میدهد.
hookها و tableهای netfilter (netfilter hooks and tables) حیاتی
به زبان ساده: هستهٔ لینوکس قاعدههای شما را در نقطههای ثابتی از مسیر بسته صدا میزند. نقطهای که انتخاب میکنید تعیین میکند بسته وقتی قاعدهتان آن را میبیند چه شکلی است (NAT شده یا نه، مقصدش این میزبان است یا جای دیگر).
بدفهمی رایج: «INPUT جایی است که همهٔ بستههای ورودی فیلتر میشوند.» فقط بستههایی که مقصدشان همین میزبان است به INPUT میرسند. بستههایی که میزبان به جای دیگر route میکند (کانتینرها، VMها، نقش router) از FORWARD میگذرند و هرگز INPUT را لمس نمیکنند. پورتهای published در Docker دقیقاً همین حالت است.
تعریف: netfilter برای IPv4 و IPv6 پنج hook تعریف میکند: prerouting (درست پس از رسیدن)، input (برای یک پردازهٔ محلی)، forward (route شده از میان میزبان)، output (از یک پردازهٔ محلی) و postrouting (درست پیش از خروج). بستههای این میزبان prerouting سپس input را میبینند؛ بستههایی که میزبان میفرستد output سپس postrouting؛ بستههای routeشده prerouting، forward، postrouting. ویکی nftables همین را میگوید: "Traffic flowing to the local machine in the input path sees the prerouting and input hooks. Then, the traffic that is generated by local processes follows the output and postrouting path." hook اضافهٔ ingress (هستهٔ ۴٫۲) به یک اینترفیس وصل میشود و پیش از prerouting و پیش از بازسازی fragmentها اجرا میشود.
iptables قاعدهها را در tableها میچیند؛ هر table هدفی دارد و در چند hook chain ثبت میکند:
| Table | Purpose | Hooks (chains) it has | Typical rule |
|---|---|---|---|
raw | Run before conntrack; mark packets as NOTRACK | PREROUTING, OUTPUT | Exempt a busy DNS server from conntrack; Docker drops direct-routed packets here |
mangle | Change packet fields (TOS, TTL, marks) | all five | Policy routing marks, MSS clamping |
nat | Rewrite addresses; consulted for the first packet of a flow only | PREROUTING (DNAT), OUTPUT, POSTROUTING (SNAT, MASQUERADE), INPUT | -j DNAT, -j MASQUERADE (see NAT) |
filter | Accept or drop | INPUT, FORWARD, OUTPUT | Your allow-list |
security | SELinux-style labels | INPUT, FORWARD, OUTPUT | Rare |
ترتیب درون یک hook با priority تعیین میشود. صفحهٔ man ابزار nft اعداد را میدهد: conntrack defrag -400، raw -300، conntrack -200، mangle -150، DNAT -100، filter 0، security 50، SNAT 100. برای همین DNAT پیش از آنکه table فیلتر بسته را ببیند اتفاق میافتد (پس FORWARD آدرس کانتینر را match میکند نه آدرس published) و SNAT بعد.
| Timeline | What the kernel does with a packet to a published container port |
|---|---|
| 1 | NIC receives the frame, conntrack creates an entry (priority -200) |
| 2 | nat PREROUTING DNAT rewrites host:8080 to 172.18.0.2:80 (priority -100) |
| 3 | Routing decision: the destination is a local bridge, not this host, so the packet goes to forward |
| 4 | filter FORWARD: DOCKER-USER, then Docker's own chains |
| 5 | nat POSTROUTING may masquerade; the frame leaves through the bridge |
سناریوهای واقعی: قاعدهٔ iptables روی INPUT که برای پورت کانتینر هیچ کاری نمیکند؛ قاعدهٔ OUTPUT که worker پیاچپی-FPM را از رسیدن به میزبان پرداخت میبندد؛ قاعدهٔ raw که یک سرویس UDP پرسروصدا را از جدول conntrack بیرون نگه میدارد.
| Product | Where its rules attach |
|---|---|
| iptables | Fixed chains in fixed tables (INPUT, FORWARD, ...) |
| nftables | Base chains you create with type filter hook input priority filter; in any table; regular chains you jump to |
| ufw | ufw-before-input, ufw-user-input and similar chains jumped to from INPUT/FORWARD/OUTPUT |
| firewalld | Zones compiled to nftables (or iptables) chains with names like filter_IN_public |
| Docker | DOCKER-USER, DOCKER-FORWARD, DOCKER, DOCKER-CT, DOCKER-BRIDGE, DOCKER-INTERNAL in filter; DOCKER in nat; PREROUTING drops in raw |
| Kubernetes kube-proxy | KUBE-SERVICES and KUBE-NODEPORTS chains in nat, KUBE-FORWARD in filter |
conntrack و ESTABLISHED,RELATED حیاتی
به زبان ساده: conntrack دفترچهٔ اتصالهای هسته است. قاعده میتواند بپرسد «آیا این بسته بخشی از اتصالی است که قبلاً اجازه دادم؟» و بدون خواندن دوبارهٔ فهرست قاعدهها آن را رد کند.
بدفهمی رایج: «ESTABLISHED یعنی handshake TCP تمام شده.» برای conntrack یعنی ترافیک در هر دو جهت دیده شده؛ جریان UDP یا ICMP هم بعد از اولین پاسخ ESTABLISHED میشود. برای همین است که محدودکنندهٔ نرخ ICMP echo که بعد از قاعدهٔ established بگذارید هرگز فعال نمیشود (آزمایشگاه نشان میدهد).
تعریف: هر بسته یکی از این وضعیتها را میگیرد که nft آن را ct state و iptables آن را -m conntrack --ctstate مینامد:
| State | Meaning | Typical rule |
|---|---|---|
new | First packet of a flow, not seen before | tcp dport 443 ct state new accept |
established | Part of a flow with traffic in both directions | ct state established,related accept (first rule) |
related | A new flow that is tied to an existing one: an ICMP error about a flow, an FTP data connection through a helper | Same rule as above |
invalid | Cannot be placed in any flow (out-of-window TCP, bogus flags) | ct state invalid drop |
untracked | Exempted with a raw rule (notrack) | You must allow these explicitly |
صفحهٔ man ابزار nft میگوید بیتهای وضعیت متقابلاً ناسازگارند، پس شکل لیستی ct state established,related و شکل set یعنی ct state { established, related } "match exactly the same packets".
$ conntrack -L -p tcp
tcp 6 116 TIME_WAIT src=172.17.0.6 dst=172.17.0.4 sport=56564 dport=18080 src=172.18.0.2 dst=172.17.0.6 sport=80 dport=56564 [ASSURED] mark=0 use=1
^ ^^^ original direction (as the client sent it) reply direction (as the server answers after DNAT)
proto number, seconds left until the entry expiresتاپل اول همان است که کلاینت فرستاد؛ دومی پاسخ مورد انتظار است. برای جریان DNATشده تاپل دوم همین حالا کانتینر (172.18.0.2:80) را نشان میدهد. هسته به همین ترتیب NAT را برمیگرداند و -m conntrack --ctorigdstport 18080 در DOCKER-USER هم میتواند پورتی را که کلاینت استفاده کرد match کند.
| Knob | Meaning | Default / note |
|---|---|---|
net.netfilter.nf_conntrack_max | Max entries in the table | Default is nf_conntrack_buckets x 4 (kernel doc); when full, new flows are dropped and the kernel logs a "table full" message |
nf_conntrack_tcp_timeout_established | Idle seconds before an established TCP entry expires | 432000 (5 days) in the kernel doc |
conntrack -C / conntrack -S | Count of entries / per-CPU statistics (insert_failed, drop) | First thing to check on a busy node |
conntrack -E | Live event stream | Watch flows appear |
سناریوهای واقعی: گرهٔ (Node) که زیر بار اتصالهای جدید را drop میکند چون conntrack پر است (به پورت، سوکت و اتصال نگاه کنید)؛ گرهٔ Kubernetes که قاعدههای kube-proxy هزاران ورودی اضافه میکند؛ سرور DNS که NOTRACK توان آن را دو برابر میکند.
نحو iptables رمزگشاییشده (iptables syntax decoded) حیاتی
به زبان ساده: دستور iptables یک جمله است: «در این table و chain یک قاعده اضافه کن که این ویژگیهای بسته را match میکند و این کار را میکند».
بدفهمی رایج: «قاعدهها مستقلاند و ترتیب مهم نیست.» اولین قاعدهٔ matchشده با verdict نهایی برنده است، پس ACCEPT گسترده بالای یک DROP مشخص آن را بیاثر میکند. و -A به انتها اضافه میکند، بعد از هر قاعدهای که از قبل همهچیز را accept میکند.
تعریف: آناتومی یک قاعده:
iptables -t filter -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
| | | | | | | |
| | | | | | | +-- target (verdict or jump)
| | | | | | +-- option of that extension
| | | | | +-- load match extension "conntrack"
| | | | +-- destination port (needs -p tcp or udp)
| | | +-- protocol
| | +-- chain; -A append, -I insert at position, -D delete, -R replace
| +-- table (default filter)
+-- the command; iptables-nft on modern distros (see nftables below)| Piece | Meaning |
|---|---|
-A, -I [n], -D, -R, -F, -X, -N | Append, insert (default position 1), delete, replace, flush chain, delete chain, new chain |
-P INPUT DROP | Set the chain policy |
-s, -d, -i, -o | Source, destination, in-interface, out-interface; ! negates |
-p tcp --dport 22, --sport, --dports 80,443 | Protocol and ports; --dports needs -m multiport |
-m state --state / -m conntrack --ctstate | Connection state (the second is current; state is the old spelling) |
-m limit --limit 5/min --limit-burst 5 | Token-bucket match, usually in front of LOG |
-m recent, -m hashlimit, -m connlimit | Per-source counters, per-source rate, per-source connection count |
-j ACCEPT, DROP, REJECT, LOG, RETURN, DNAT, MASQUERADE, or a chain name | Target; DROP is silent, REJECT answers with an error |
خروجی واقعی یک INPUT با default-deny که دستی ساخته شده و با سه دستور ممیزی فهرست شده. در یک کانتینر Alpine با --cap-add NET_ADMIN:
$ iptables -P INPUT DROP
$ iptables -A INPUT -i lo -j ACCEPT
$ iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
$ iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
$ iptables -A INPUT -m limit --limit 5/min -j LOG --log-prefix "ipt-drop: "
$ iptables -S
-P INPUT DROP
-P FORWARD ACCEPT
-P OUTPUT ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
-A INPUT -m limit --limit 5/min -j LOG --log-prefix "ipt-drop: "
$ iptables -L INPUT -v -n --line-numbers
Chain INPUT (policy DROP 0 packets, 0 bytes)
num pkts bytes target prot opt in out source destination
1 0 0 ACCEPT all -- lo * 0.0.0.0/0 0.0.0.0/0
2 0 0 ACCEPT all -- * * 0.0.0.0/0 0.0.0.0/0 ctstate RELATED,ESTABLISHED
3 0 0 ACCEPT tcp -- * * 0.0.0.0/0 0.0.0.0/0 tcp dpt:22 ctstate NEW
4 0 0 LOG all -- * * 0.0.0.0/0 0.0.0.0/0 limit: avg 5/min burst 5 LOG flags 0 level 4 prefix "ipt-drop: "iptables -S دستورهایی را چاپ میکند که میتوانید دوباره اجرا کنید؛ iptables -L -v -n شمارندهها (بسته و بایت به ازای هر قاعده) را چاپ میکند، -n جستجوی DNS را رد میکند و --line-numbers موقعیتی را میدهد که به -D و -I میدهید. iptables-save و iptables-restore کل مجموعهقاعده را اتمیک ذخیره و بارگذاری میکنند.
سناریوهای واقعی: قاعدهٔ SSH با محدودیت SYN-flood؛ DNAT برای port forward؛ -j REJECT --reject-with tcp-reset برای سرویس داخلی که باید سریع شکست بخورد.
| Product | Notes |
|---|---|
| iptables-legacy (xtables) | The original kernel interface; separate binaries per family (iptables, ip6tables, arptables, ebtables) |
| iptables-nft | The same command line, but rules are stored as nftables rules; iptables --version prints (nf_tables) |
| iptables-restore | Atomic bulk load; the right way to change many rules |
nftables: جانشین (the successor) حیاتی
به زبان ساده: nftables همان موتور بستهٔ هسته است با یک ابزار (nft)، یک زبان قاعده و ساختارهای set و map که اجازه میدهند یک قاعده فهرستی از ده هزار آدرس را match کند.
بدفهمی رایج: «iptables و nftables دو فایروالاند، یکی را انتخاب کن.» در توزیعهای امروزی دستور iptables معمولاً یک shim است که قاعدهٔ nftables مینویسد (iptables-nft)؛ هر دو نما همان وضعیت هسته را نشان میدهند. اشتباه گرفتن بیدقت این دو مشکل میسازد، نه همزیستیشان.
تعریف: nftables هیچ table یا chain از پیش تعریفشدهای ندارد. یک table در یک خانوادهٔ آدرس (ip، ip6، inet برای هر دو، arp، bridge، netdev) میسازید، سپس base chainها که به hook با priority و policy وصل میشوند و chainهای معمولی که به آنها jump میزنید. ویکی nftables: "In a major change from iptables, which predefines chains at every hook (i.e. INPUT chain in filter table), nftables predefines no chains at all."
خروجی واقعی nft list ruleset یک وبسرور default-deny با set نامدار و ICMP محدودشده (فایل کامل web-server.nft است):
table inet filter {
set admin_v4 {
type ipv4_addr
flags interval
elements = { 10.0.0.0/8, 172.16.0.0/12 }
}
chain input {
type filter hook input priority filter; policy drop;
ct state invalid counter packets 0 bytes 0 drop
ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
ct state established,related accept
iifname "lo" accept
tcp dport { 80, 443 } ct state new accept
ip saddr @admin_v4 tcp dport 22 ct state new accept
limit rate 5/minute burst 5 packets log group 100 prefix "nft-input-drop: " counter packets 2 bytes 120
}
chain forward { type filter hook forward priority filter; policy drop; }
chain output { type filter hook output priority filter; policy accept; }
}| nftables idea | Syntax | Why it beats iptables |
|---|---|---|
| One table for both families | table inet filter | One rule covers IPv4 and IPv6; no ip6tables twin |
| Anonymous set | tcp dport { 80, 443 } | One rule instead of two, evaluated as a set |
| Named set | set admin_v4 { type ipv4_addr; flags interval; } then ip saddr @admin_v4 | Update the set at runtime with nft add element; no rule reload |
| Interval sets | flags interval, elements = { 10.0.0.0/8 } | CIDR blocks as set members |
| Dynamic sets and meters | flags dynamic, timeout; update @s { ip saddr limit rate 3/minute } | Per-source rate limits (iptables hashlimit, recent) |
| Maps | dnat to tcp dport map { 80 : 10.0.0.5, 443 : 10.0.0.6 } | A lookup table as an action: one rule for many port forwards |
| Concatenations | ip saddr . tcp dport @allowed | A set of pairs: "address X may reach port Y" in one lookup |
| Atomic reload | nft -f file | The whole file applies or none of it does |
shim و مترجم دستورهای واقعیاند. خروجی واقعی از Alpine با iptables v1.8.13 (nf_tables):
$ iptables-translate -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'
$ iptables-translate -t nat -A POSTROUTING -s 10.0.0.0/24 -o eth0 -j MASQUERADE
nft 'add rule ip nat POSTROUTING oifname "eth0" ip saddr 10.0.0.0/24 counter masquerade'
$ nft list ruleset # after the iptables commands above
table ip filter {
chain INPUT {
type filter hook input priority filter; policy drop;
iifname "lo" counter packets 0 bytes 0 accept
...
# Warning: table ip filter is managed by iptables-nft, do not touch!آن خط آخر هشداری است که باید جدی گرفت: tableای که iptables-nft ساخته باید با iptables تغییر کند، نه با nft. قاعدههای nftables خودتان را در table جدا (table inet myfw) بگذارید تا کنار آن زندگی کنند.
سناریوهای واقعی: فایروالی با blocklist پنجاههزارتایی بهصورت یک set؛ جدول port-forward بهصورت یک map؛ میزبانی که اتمیک از فایل زیر Git دوباره بارگذاری میشود؛ سروری dual-stack که یک table از نوع inet چهار دستور iptables را جایگزین میکند.
| Product | nftables status |
|---|---|
| Current Debian, Ubuntu, RHEL and Fedora releases | iptables is the nft shim by default (check iptables --version) |
| firewalld | nftables backend in current releases |
| Docker | iptables backend by default; the Docker page documents an nftables backend, marked experimental there, in which "there is no DOCKER-USER chain" |
| Kubernetes kube-proxy | iptables and ipvs modes; an nftables mode also exists |
| Cilium | eBPF datapath; does not use iptables for policy |
ufw و firewalld: front-endها (ufw and firewalld) مهم
به زبان ساده: ufw و firewalld ابزارهای دوستانهتریاند که قاعدهٔ iptables یا nftables را برای شما مینویسند. بیشتر قاعدههای واقعی سرورها از همینها میآید.
بدفهمی رایج: «ufw یک فایروال است.» front-end برای netfilter است و فقط chainهایی را مدیریت میکند که مال خودش است (INPUT، FORWARD، OUTPUT). هر چیزی که دور این chainها میپیچد، مثل DNAT بهاضافهٔ قاعدههای FORWARD در Docker، بیرون از دسترس آن است.
تعریف: صفحهٔ man ابزار ufw: ufw یک "program for managing a netfilter firewall" است؛ "On installation, ufw is disabled with a default incoming policy of deny, a default forward policy of deny, and a default outgoing policy of allow, with stateful tracking for NEW connections for incoming and forwarded connections." firewalld خودش را "a simple, stateful, zone-based firewall" توصیف میکند: ترافیک وارد یک zone و خارج از یک zone میشود، zone سطح اعتماد را تعیین میکند، درون-zone بهصورت پیشفرض مجاز و بین-zone ممنوع است.
$ ufw default deny incoming
$ ufw default allow outgoing
$ ufw allow from 10.0.0.0/8 to any port 22 proto tcp
$ ufw allow 443/tcp
$ ufw limit 22/tcp # rate limit: ufw denies a source that opens many new connections in a short time
$ ufw enable && ufw status verbose$ firewall-cmd --permanent --zone=public --add-service=https
$ firewall-cmd --permanent --zone=internal --add-source=10.0.0.0/8
$ firewall-cmd --permanent --zone=internal --add-port=22/tcp
$ firewall-cmd --reload
$ firewall-cmd --list-all-zones| Question | ufw | firewalld |
|---|---|---|
| Default distributions | Ubuntu, Debian-family | RHEL, Fedora, CentOS Stream, SUSE |
| Model | Allow/deny/reject/limit rules with a default policy | Zones, services, rich rules, policies between zones |
| Backend | iptables or nftables (via the iptables-nft shim) | nftables by default |
| Change without restart | ufw allow ... | firewall-cmd --add-service (runtime) plus --permanent and --reload |
| Docker interaction | Docker's published ports bypass it | Docker creates a docker zone with target ACCEPT and a docker-forwarding policy |
لاگ و محدودکردن نرخ (Logging and rate limiting) مهم
به زبان ساده: drop بیصداست. برای فهمیدن اینکه فایروال چه چیزی را دور میریزد درست پیش از drop یک قاعدهٔ log میگذارید و نرخش را سقف میزنید تا یک اسکن دیسک را پر نکند.
بدفهمی رایج: «هر چه را drop میکنم لاگ میکنم.» میزبان شلوغ میلیونها بسته drop میکند؛ لاگ نامحدود خودش خرابی میشود. نمونه لاگ کنید (limit rate 5/minute) و برای بقیه شمارنده نگه دارید.
تعریف: nftables دستور log دارد (لاگ هسته، یا log group N برای فرستادن به user space از راه nflog) و counter. iptables هدفهای LOG و NFLOG را دارد. محدودکردن نرخ یک سطل توکن (Token bucket) است: limit rate 5/second burst 10 packets. محدودیت بهازای هر مبدأ از set پویا (Dynamic set) استفاده میکند (در ویکی به آن meter میگویند: "ratelimit inbound TCP connections to port 22 per source IP address").
# per-source SSH rate limit: three new connections per minute per address, the rest is dropped
table inet filter {
set ssh_meter { type ipv4_addr; flags dynamic; timeout 60s; }
chain input {
type filter hook input priority filter; policy drop;
ct state established,related accept
tcp dport 22 ct state new update @ssh_meter { ip saddr limit rate 3/minute } accept
}
}ضبط واقعی dropهای لاگشده از راه گروه nflog شمارهٔ ۱۰۰ با tcpdump (لاگ هسته داخل کانتینر بیامتیاز دیده نمیشود؛ nflog دیده میشود):
$ tcpdump -l -n -i nflog:100
17:42:11.697290 IP 172.19.0.3.41840 > 172.19.0.2.5432: Flags [S], seq 2330625817, win 64240, length 0
1 packet capturedفقط یک SYN دیده میشود با اینکه دو بسته drop شد: قاعدهٔ لاگ به burst پنج محدود است و آزمایش قبلی سطل را مصرف کرده بود. این همان محدودکننده است که کارش را میکند.
| Tool | Does what |
|---|---|
log / LOG | Writes to the kernel ring buffer (dmesg, journalctl -k); prefix tells you which rule |
log group N / NFLOG | Sends the packet to a userspace listener (tcpdump -i nflog:N, ulogd) |
counter | Packets and bytes per rule; no log volume |
limit rate | Token bucket per rule |
| Meters (dynamic sets) | Per-source buckets with a timeout |
| fail2ban | Reads auth logs and inserts per-IP drop rules into a set or chain for a time |
| CrowdSec | Shared blocklists; ban decisions written to nft sets |
سناریوهای واقعی: لاگ پنج drop اول در دقیقه با prefix مخصوص هر chain؛ fail2ban که IP یک brute-force را روی پورت ۲۲ مسدود میکند؛ meterی که اتصالهای جدید هر کلاینت به API را سقف میزند.
ICMP: چرا نباید همهٔ آن را بست (ICMP, PMTUD) حیاتی
به زبان ساده: ICMP کانال خطای شبکه است. وقتی بسته برای یک لینک بزرگ است router با یک پیام ICMP «خیلی بزرگ» جواب میدهد و فرستنده بستههایش را کوچک میکند. اگر فایروال این پیام را ببلعد فرستنده هرگز نمیفهمد و انتقالهای بزرگ گیر میکنند در حالی که کوچکها کار میکنند.
بدفهمی رایج: «ICMP فقط ping است، پس بستنش سختسازی است.» ping (echo request) یکی از انواع ICMP است. Destination unreachable (نوع ۳، از جمله کد ۴ «fragmentation needed») و time exceeded ضروریاند؛ RFC 4890 برای IPv6 فهرست «Traffic That Must Not Be Dropped» دارد که با Destination Unreachable، Packet Too Big، Time Exceeded و Parameter Problem شروع میشود.
تعریف: کشف MTU مسیر (Path MTU Discovery؛ RFC 1191 برای IPv4 با بیت DF؛ IPv6 همین سازوکار را دارد و routerها هرگز fragment نمیکنند) کار میکند چون routerها بستهٔ بزرگ را drop میکنند و پیام ICMP با MTU گام بعدی برمیگردانند. RFC 4890 دربارهٔ IPv6: پیام Packet Too Big "is vital to the correct functioning of Path MTU Discovery". RFC 4821 راه جایگزینی را شرح میدهد که black holeها را بدون ICMP تشخیص میدهد (Packetization Layer PMTUD؛ در لینوکس با net.ipv4.tcp_mtu_probing فعال میشود).
1 client -> server TCP 1500-byte packet, DF=1 (e.g. a TLS record in a large upload)
2 router (link MTU 1400) drops it, sends ICMP type 3 code 4 "fragmentation needed, next-hop MTU 1400"
3a firewall allows ICMP -> client lowers its MSS, resends in 1360-byte segments, works
3b firewall drops ICMP -> client never hears, retransmits the same size, hangs (MTU black hole)یک ICMP echo request واقعی که به همان شکل ضبط شده (چیدمان هدر همان است که icmp type و icmp code match میکنند):
0x0000: 3e20 ea32 077e 4660 4252 9bd4 0800 4500
0x0010: 0024 5359 4000 4001 8f54 ac13 0003 ac13 <- 0x17: protocol 01 = ICMP
0x0020: 0002 0800 c03a 006c 0000 d1a2 65b6 0000 <- 0x22: type 08 (echo request), code 00, checksum c03a, id 006c, seq 0000| ICMP message | IPv4 type/code | ICMPv6 type | Allow in? | Why |
|---|---|---|---|---|
| Destination unreachable (incl. fragmentation needed) | 3 / 0-15, 3/4 | 1 | Yes | Errors for flows you started; PMTUD |
| Packet Too Big | (3/4 on IPv4) | 2 | Yes | PMTUD on IPv6; routers do not fragment |
| Time exceeded | 11 | 3 | Yes | traceroute, loops |
| Parameter problem | 12 | 4 | Yes | Header errors |
| Echo request / reply | 8 / 0 | 128 / 129 | Optional, rate-limited | Reachability checks; RFC 4890 says IPv6 echo need not be filtered |
| Neighbor / router discovery | n/a (ARP) | 133-136 | Yes on IPv6 | NDP replaces ARP; blocking it breaks the LAN |
| Redirect | 5 | 137 | No | Can steer traffic |
سناریوهای واقعی: VPN یا تونلی با MTU ۱۴۰۰ که در آن curl به صفحهٔ کوچک کار میکند ولی آپلود فایل گیر میکند؛ security groupی که فقط «TCP 443» دارد و ICMP ندارد، پشت لینک Geneve یا WireGuard؛ صفحهٔ NACL خود AWS که بخشی با عنوان «Path MTU Discovery and network ACLs» دارد.
راهحل: ICMP خطاها را در هر سیاست default-deny اجازه دهید (مثل قاعدههای آزمایشگاه)، echo را محدود کنید و جایی که مسیر دست شما نیست MSS را clamp کنید (iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --clamp-mss-to-pmtu).
| Product | How to allow the essential ICMP |
|---|---|
| nftables | ip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem } accept; meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, ... } accept |
| iptables | -p icmp --icmp-type destination-unreachable -j ACCEPT, and ip6tables -p ipv6-icmp -j ACCEPT |
| AWS security group | Add an inbound rule: custom ICMP, type 3 code 4 (fragmentation needed) and ICMPv6 type 2; the stateful SG returns errors for tracked flows |
| AWS network ACL | The AWS NACL page has a PMTUD section; add an inbound ICMP rule for type 3 code 4 |
| Kubernetes NetworkPolicy | "behaviour is undefined" for ARP and ICMP; depends on the CNI |
فایروال IPv6: NAT نیست که پشتش پنهان شوید (IPv6 firewalling) حیاتی
به زبان ساده: با IPv4 در خانه، NAT اتفاقاً اتصالهای ورودی ناخواسته را میبست. با IPv6 هر دستگاه آدرس عمومی دارد و فقط فایروال بین آن و اینترنت است.
بدفهمی رایج: «کسی آدرس IPv6 را پیدا نمیکند، خیلی زیاد است.» RFC 4864 میگوید اسکن یک زیرشبکهٔ ۶۴ بیتی هزاران سال طول میکشد، اما میزبانها آدرسشان را از راه DNS، لاگها، certificate transparency و آدرسهای EUI-64 پیشبینیپذیر یا کمشماره نشت میدهند. همان RFC: "IPv4 NAT was not developed as a security mechanism."
تعریف: هر قاعدهٔ IPv6 به یک همتای IPv6 نیاز دارد؛ فراموشکردن ip6tables ماشین را روی IPv6 کاملاً باز میگذارد در حالی که IPv4 قفل به نظر میرسد. در nftables خانوادهٔ inet هر دو را با یک مجموعهقاعده پوشش میدهد. IPv6 به ICMPv6 (neighbor discovery، packet too big) هم نیاز دارد وگرنه شبکه از کار میافتد، و فیلتر ip6 nexthdr فقط هدر اول را میبیند: man ابزار nft هشدار میدهد "ip6 nexthdr tcp will only match if the ipv6 packet does not contain any extension headers"، پس از meta l4proto tcp استفاده کنید (که "will also skip any IPv6 extension headers").
# WRONG: IPv4 closed, IPv6 wide open (the iptables habit)
iptables -P INPUT DROP
# ip6tables -P INPUT DROP <- forgotten
# RIGHT: one inet table, same rules for both families
table inet filter { chain input { type filter hook input priority filter; policy drop; ... } }سناریوهای واقعی: VM ابری با IPv6 عمومی و security groupی که فقط قاعدهٔ IPv4 دارد (قاعدهٔ IPv6 در AWS، GCP و Azure ورودی جدا برای ::/0 است)؛ خوشهٔ dual-stack در Kubernetes با ipBlock در NetworkPolicy فقط برای IPv4؛ router خانگی که IPv6 را بدون فایروال forward میکند.
| Product | IPv6 detail |
|---|---|
| AWS security group | Separate rules for ::/0 and IPv6 CIDRs; one SG can hold both |
| AWS network ACL | "IPv4 and IPv6 traffic are evaluated separately"; IPv6 rules have their own numbers |
| GCP | Source and destination ranges accept IPv4 and IPv6 CIDRs; the API says "Both IPv4 and IPv6 are supported" |
| Linux | ip6tables, or inet family in nftables; ufw manages both when IPV6=yes |
| Docker | ip6tables option and its own IPv6 chains; IPv6 publishing is covered below |
Docker و فایروالها (Docker and firewalls) حیاتی
به زبان ساده: Docker قاعدهٔ فایروال خودش را مینویسد. پورت published (-p 8080:80) را Docker برای همه باز میکند، در بخشی از فهرست قاعدهها که قاعدههای ufw شما هرگز آن را نمیبینند.
بدفهمی رایج: «ufw deny 5432 از Postgres published من محافظت میکند.» مستندات Docker عکسش را صریح میگوید: "Docker routes container traffic in the nat table, which means that packets are diverted before it reaches the INPUT and OUTPUT chains that ufw uses." و: "Publishing container ports is insecure by default. Meaning, when you publish a container's ports it becomes available not only to the Docker host, but to the outside world as well."
تعریف: Docker در table فیلتر chainهای DOCKER-USER ("a placeholder for user-defined rules that will be processed before rules in the DOCKER-FORWARD and DOCKER chains")، DOCKER-FORWARD، DOCKER، DOCKER-BRIDGE، DOCKER-INTERNAL، DOCKER-CT و برای Swarm DOCKER-INGRESS را میسازد؛ در table nat یک chain به نام DOCKER با قاعدههای DNAT؛ و در table raw قاعدههای drop در PREROUTING برای دسترسی direct-routed. همچنین IP forwarding را روشن میکند و با backend iptables policy زنجیرهٔ FORWARD را روی DROP میگذارد تا فقط آنچه Docker accept میکند forward شود.
قاعدههای واقعی روی Docker 29.10 (داخل یک daemon از نوع Docker-in-Docker) پس از docker run -d -p 18080:80 nginx:alpine و -p 127.0.0.1:18081:80:
$ iptables -S FORWARD
-P FORWARD ACCEPT
-A FORWARD -j DOCKER-USER
-A FORWARD -j DOCKER-FORWARD
$ iptables -t nat -S DOCKER
-N DOCKER
-A DOCKER ! -i docker0 -p tcp -m tcp --dport 18080 -j DNAT --to-destination 172.18.0.2:80
-A DOCKER -d 127.0.0.1/32 ! -i docker0 -p tcp -m tcp --dport 18081 -j DNAT --to-destination 172.18.0.5:80
$ iptables -t raw -S
-P PREROUTING ACCEPT
-A PREROUTING -d 172.18.0.2/32 ! -i docker0 -j DROP
-A PREROUTING -d 127.0.0.1/32 ! -i lo -p tcp -m tcp --dport 18081 -j DROPاولین قاعدهٔ PREROUTING بستههایی را که مستقیم به آدرس خود کانتینر از خارج پل فرستاده شود drop میکند، پس فقط پورت published کار میکند. دومی اصلاح Docker 28 برای پورتهای published روی loopback است (پایینتر را ببینید).
| Timeline | Experiment (all real, run from two other containers as "external" clients) |
|---|---|
| 1 | ext1 and ext2 reach the published port: wget http://172.17.0.4:18080/ succeeds for both |
| 2 | Real ufw 0.36.2 is installed in the same Docker host (ufw default deny incoming, ufw allow 22/tcp, ufw enable) and ufw deny 18080/tcp is added; ufw status lists it as DENY and the INPUT policy is DROP. ext1 still gets the page and the ufw-user-input DROP rule for 18080 stays at 0 packets |
| 3 | iptables -I DOCKER-USER -i eth0 ! -s 172.17.0.5 -p tcp -m conntrack --ctorigdstport 18080 -j DROP goes in |
| 4 | ext1 (172.17.0.5) still succeeds; ext2 times out ("download timed out"); the rule's counter shows 3 packets dropped |
چطور پورتهای published را درست محدود کنیم:
| Goal | How | Why it works |
|---|---|---|
| Only the host (or a reverse proxy on the host) reaches it | -p 127.0.0.1:8080:80 (and -p '[::1]:8080:80') | "If you include the localhost IP address (127.0.0.1, or ::1) with the publish flag, only the Docker host can access the published container port." |
| Only some clients reach it | A rule at the top of DOCKER-USER, matching the original port: iptables -I DOCKER-USER -i ext_if ! -s 192.0.2.0/24 -p tcp -m conntrack --ctorigdstport 8080 -j DROP | DOCKER-USER runs before Docker's rules; DNAT has already rewritten the destination, so you match the original with conntrack |
| Allow replies | iptables -I DOCKER-USER -m state --state RELATED,ESTABLISHED -j ACCEPT placed before the drops | Containers' outgoing flows must come back |
| Everything private by default | Change the default publish address: daemon ip: 127.0.0.1, or network option com.docker.network.bridge.host_binding_ipv4=127.0.0.1 | New -p flags bind to loopback unless you name an address |
| Not published at all | Same user-defined network, no -p; talk by container name | Containers reach each other on the bridge; nothing is reachable from outside |
| nftables backend | Create your own table with a forward-hook base chain and a lower priority number than Docker's | "In Docker's nftables implementation, there is no DOCKER-USER chain" |
آنچه در Docker 28 تغییر کرد (رفتار مستند). صفحهٔ port-publishing در Docker هشدار میدهد: "In releases older than 28.0.0, hosts within the same L2 segment (for example, hosts connected to the same network switch) can reach ports published to localhost." صفحههای iptables و nftables در Docker رفتار فعلی direct routing را هم اضافه میکنند: بستههایی که مستقیم به آدرس کانتینر فرستاده شوند با قاعدههای raw بالا drop میشوند مگر با com.docker.network.bridge.trusted_host_interfaces، گزینهٔ daemon به نام allow-direct-routing یا حالت gateway به نام nat-unprotected صراحتاً اجازه دهید. پورت published روی 0.0.0.0 هنوز برای همه باز است؛ پس Docker 28 درهای کناری را میبندد، نه در جلو را.
سناریوهای واقعی: فایل Compose با ports: ["5432:5432"] روی VM ابری که security groupاش برای همه باز است؛ میزبان CI که ufw status در آن «deny» نشان میدهد و Redis در معرض همچنان جواب میدهد؛ سرور staging که bind روی 127.0.0.1: و یک nginx روی میزبان تنها راه ورود است.
| Product | What to do |
|---|---|
| Docker (iptables backend) | Bind to 127.0.0.1 or use DOCKER-USER; keep iptables: true |
| Docker (nftables backend) | Your own table with a forward base chain; mark-based accepts via --bridge-accept-fwmark |
| ufw | Does not control published ports; use ufw-docker-style rules in DOCKER-USER, or bind to loopback |
| firewalld | Docker adds a docker zone, target ACCEPT; restrict with a rich rule or a policy |
| Podman | Uses netavark with its own nftables/iptables chains; rootless Podman publishes through a userspace proxy |
| Compose | Same flags: ports: ["127.0.0.1:8080:80"] |
Kubernetes NetworkPolicy حیاتی
به زبان ساده: NetworkPolicy میگوید کدام Podها میتوانند با کدام Podها حرف بزنند، با label. تا وقتی سیاستی یک Pod را انتخاب نکند آن Pod همهچیز را میپذیرد و میفرستد.
بدفهمی رایج: «YAML را apply کردم، پس ترافیک محدود شد.» مستندات Kubernetes صریح است: "Creating a NetworkPolicy resource without a controller that implements it will have no effect." API server شیء را ذخیره میکند؛ پلاگین شبکه (CNI) اجرایش میکند و همه این کار را نمیکنند.
تعریف: Pod وقتی برای ingress ایزوله (isolated) است که یک NetworkPolicy آن را انتخاب کند و Ingress را در policyTypes داشته باشد؛ برای egress هم همینطور. Podِ ایزوله فقط آنچه اجتماع سیاستهای matchشده اجازه میدهد میپذیرد ("The effects of those ingress lists combine additively"، پس ترتیب مهم نیست و قاعدهٔ deny وجود ندارد). یک اتصال به هر دو نیاز دارد: egress مبدأ و ingress مقصد باید اجازه دهند. ترافیک پاسخ ضمناً مجاز است. ترافیک از و به گرهٔ خود Pod همیشه مجاز است و Pod نمیتواند دسترسی به خودش را ببندد.
قاعدههای selector جایی است که مردم اشتباه میکنند. در فهرست from یا to هر آیتم فهرست با OR ترکیب میشود؛ داخل یک آیتم selectorها با AND:
from:
- namespaceSelector: {matchLabels: {user: alice}} # item 1: ANY pod in namespaces labelled user=alice
- podSelector: {matchLabels: {role: client}} # item 2: OR pods role=client in THIS namespace
from:
- namespaceSelector: {matchLabels: {user: alice}} # one item, two selectors = AND:
podSelector: {matchLabels: {role: client}} # pods role=client in namespaces user=alicenamespace فیلد نامی برای match ندارد، اما "The Kubernetes control plane sets an immutable label kubernetes.io/metadata.name on all namespaces"، پس روی همان label match کنید.
گام ۱، default-deny برای هر دو جهت در یک namespace (الگوی مستندات Kubernetes):
# Step 1: isolate every pod in the namespace for ingress AND egress.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: default-deny-all
namespace: shop
spec:
podSelector: {}
policyTypes: [Ingress, Egress]گام ۲: سیاست default-deny برای egress "also blocks DNS traffic"، پس آن را اجازه دهید:
# Step 2: without this, a default-deny egress policy breaks name resolution too.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: allow-dns-egress
namespace: shop
spec:
podSelector: {}
policyTypes: [Egress]
egress:
- to:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: kube-system
podSelector:
matchLabels:
k8s-app: kube-dns
ports:
- { protocol: UDP, port: 53 }
- { protocol: TCP, port: 53 }گام ۳ و ۴: اجازه دهید ingress controller به API برسد، API به پایگاهداده برسد و API به یک CIDR بیرونی برسد:
# Step 3: the api pods accept traffic on 8080 only from the ingress controller's namespace
# AND only from pods labelled as the controller (one `from` item with BOTH selectors = AND).
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-ingress
namespace: shop
spec:
podSelector:
matchLabels: { app: api }
policyTypes: [Ingress]
ingress:
- from:
- namespaceSelector:
matchLabels:
kubernetes.io/metadata.name: ingress-nginx
podSelector:
matchLabels:
app.kubernetes.io/name: ingress-nginx
ports:
- { protocol: TCP, port: 8080 }# Step 4: the database accepts 5432 only from api pods in the same namespace,
# and the api may reach the database and an external payments CIDR, nothing else.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-ingress
namespace: shop
spec:
podSelector:
matchLabels: { app: db }
policyTypes: [Ingress]
ingress:
- from:
- podSelector:
matchLabels: { app: api }
ports:
- { protocol: TCP, port: 5432 }
---
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: api-egress
namespace: shop
spec:
podSelector:
matchLabels: { app: api }
policyTypes: [Egress]
egress:
- to:
- podSelector:
matchLabels: { app: db }
ports:
- { protocol: TCP, port: 5432 }
- to:
- ipBlock:
cidr: 203.0.113.0/24 # payments provider (documentation range)
ports:
- { protocol: TCP, port: 443 }| Field | Meaning | Trap |
|---|---|---|
podSelector: {} | All pods in the policy's namespace | Empty selector means everything, not nothing |
policyTypes | Ingress, Egress or both | If omitted, Ingress is always set; Egress only if the policy has egress rules |
ingress[].from / egress[].to | List of peers: podSelector, namespaceSelector, ipBlock | AND within an item, OR between items |
ipBlock | A CIDR with optional except | Meant for cluster-external IPs; Service or NodePort rewriting may happen before or after policy ("not defined"), so the source seen can be a node or load balancer |
ports[].port, endPort | A port or a range | The CNI must support endPort, otherwise only the single port is applied |
protocol | TCP, UDP, SCTP | For ICMP and ARP the behaviour is undefined |
ingress: [{}] | Allow all ingress | Used to override or document openness |
NetworkPolicy چه کارهایی نمیتواند بکند (فهرست مستندات): لاگکردن اتصالهای مجاز یا ردشده، deny صریح (مدل فقط allow است)، هدفگرفتن Service با نام، اعمال سیاست پیشفرض روی همهٔ namespaceها (API چنین چیزی ندارد)، هر چیز مربوط به TLS، بستن ترافیک host-local یا گره. اینها افزونههای CNI (CRDهای سیاست Cilium و Calico) یا قلمرو service mesh است.
اجرا: CNI باید پشتیبانی کند. صفحهٔ "Install a Network Policy Provider" در مستندات Antrea، Calico، Cilium و Kube-router را فهرست میکند. مستندات kind شبکهٔ پیشفرضش را "a simple networking implementation (kindnetd)" مینامد که میتوانید با disableDefaultCNI: true عوضش کنید و میگوید "many common CNI manifests are known to work, e.g. Calico"؛ این امنترین راه آزمودن policy در kind است. Calico و Cilium سیاست را با برنامهریزی iptables/ipset (Calico) یا eBPF (Cilium: "At the foundation of Cilium is a new Linux kernel technology called eBPF") پیاده میکنند. با eBPF فهرست قاعدهها مجموعهای از lookupهای hash در هسته است نه chain خطی iptables، و سیاست میتواند هویتها و نامهای DNS (قاعدهٔ FQDN) را match کند که NetworkPolicy ساده نمیتواند. یعنی گرههای Kubernetes ممکن است برای آن سیاست هیچ قاعدهٔ iptables نشان ندهند: از ابزار خود CNI (cilium monitor، calicoctl) استفاده کنید نه iptables -S.
| CNI | Enforces core NetworkPolicy? | Extra policy API |
|---|---|---|
| Calico | Yes | GlobalNetworkPolicy, deny rules, ordering, host endpoints |
| Cilium | Yes (eBPF) | CiliumNetworkPolicy, FQDN egress, L7 HTTP/Kafka rules, Hubble flow logs |
| Antrea, Kube-router | Yes | Own CRDs (Antrea) |
| kind default (kindnetd) | Check before relying on it; install Calico with disableDefaultCNI: true | None |
| A CNI with no policy controller | No: the object is stored and ignored | None |
| Managed clusters (EKS, GKE, AKS) | Needs the provider's policy engine switched on or a plugin installed | Provider-specific |
چرخهٔ عمر Pod: Podای که پیش از تمامشدن برنامهریزی یک سیاست جدید توسط controller شروع شود "may start unprotected"؛ سیاست برای اتصالهای در حال جریان عطف به ماسبق نمیشود ("implementation defined").
$ kubectl -n shop get networkpolicy
$ kubectl -n shop describe networkpolicy api-ingress # shows how the selectors were interpreted
$ kubectl -n shop exec other -- curl -s -m 3 http://$DB_IP:5432 # timeout = dropped, not refusedسناریوهای واقعی: خوشهٔ چندمستاجره که هر namespace یک default-deny و یک سیاست allow-DNS از الگو میگیرد؛ پایگاهدادهای که فقط Podهای API میرسند؛ namespaceای که egressش به یک CIDR پرداخت محدود است؛ Podهای kube-system که مثل قبل به همهجا میرسند.
فایروالهای ابری: security group، NACL، قاعدههای GCP، NSG در Azure (Cloud firewalls) حیاتی
به زبان ساده: security group ابری فایروالی است که به کارت شبکهٔ یک سرور وصل میکنید؛ network ACL فایروال دومی در لبهٔ یک زیرشبکه است. پیش از رسیدن بسته به سیستمعامل فیلتر میکنند، پس هیچ iptablesای دخیل نیست و هیچکس روی ماشین نمیتواند خاموششان کند.
بدفهمی رایج: «security group و NACL دو نام برای یک چیزند.» در دامنه، حالتداری و مدل قاعده فرق دارند. جدول خود مستندات AWS: security group در سطح instance، "Allow rules only"، "Evaluates all rules before deciding" و ترافیک برگشت "Automatically allowed (stateful)" است؛ network ACL در سطح زیرشبکه، "Allow and deny rules"، "Evaluates rules in ascending order until a match" و ترافیک برگشت "Must be explicitly allowed (stateless)" است.
تعریف (AWS). security group به رابطهای شبکه (ENI) وصل میشود، پس دنبال instance، load balancer یا ENI مربوط به Lambda میرود. "You can specify allow rules, but not deny rules." گروه جدید قاعدهٔ ورودی ندارد و یک قاعدهٔ allow-all خروجی دارد. مبدأ یا مقصد قاعده میتواند CIDR، prefix list یا security group دیگری باشد ("security group referencing")، که بدون آدرس میگوید «لایهٔ وب میتواند به لایهٔ DB برسد». چند گروه روی یک ENI با هم اجتماع میشوند. network ACL به یک زیرشبکه وصل است؛ هر قاعده شمارهٔ ۱ تا ۳۲۷۶۶ دارد و به ترتیب ارزیابی میشود؛ قاعدهٔ نهایی * همهچیز را رد میکند. بیحالت است: "If, for example, you create a NACL rule to allow specific inbound traffic to a subnet, responses to that traffic are not automatically allowed."
Inbound to the web server (TCP 443 from a browser at 198.51.100.9:51344)
NACL IN rule 100 allow tcp 443 from 0.0.0.0/0 -> match, stop
SG IN allow tcp 443 from 0.0.0.0/0 -> match
Outbound reply (server 10.0.1.25:443 -> 198.51.100.9:51344)
SG OUT no rule needed: connection tracking says "reply"
NACL OUT rule 100 allow tcp 1024-65535 to 0.0.0.0/0 -> REQUIRED, otherwise the reply is dropped at the subnet edgeبازهٔ ephemeral را سیستمعامل کلاینت انتخاب میکند: صفحهٔ AWS میگوید "Many Linux kernels (including the Amazon Linux kernel) use ports 32768-61000. Requests originating from Elastic Load Balancing use ports 1024-65535. ... Windows Server 2008 and later versions use ports 49152-65535. A NAT gateway uses ports 1024-65535." در عمل روی NACL برای جهت برگشت ۱۰۲۴ تا ۶۵۵۳۵ را باز کنید.
جزئیات connection tracking که میگزد (مستندات EC2): "When you change a security group rule, its tracked connections are not immediately interrupted. The security group continues to allow packets until existing connections time out." جریانی که با جفت قاعدهٔ کاملاً باز (0.0.0.0/0 در هر دو جهت) اجازه گرفته ردیابی نمیشود (untracked)، پس برداشتن آن قاعده نشست را فوراً قطع میکند. برای پروتکلهایی غیر از TCP، UDP و ICMP فقط آدرس و شمارهٔ پروتکل ردیابی میشود، با پنجرهٔ ۶۰۰ ثانیه. نه security group و نه NACL ترافیک به Route 53 Resolver، DHCP، instance metadata (IMDS) یا Time Sync Service را فیلتر نمیکنند؛ برای آنها DNS Firewall و گزینههای IMDS را به کار ببرید.
GCP و Azure. قاعدههای فایروال VPC در GCP به یک شبکهٔ VPC وصلاند و instanceها را با target tag یا target service account انتخاب میکنند ("If targetTags are specified, then the firewall rule applies only to instances in the VPC network that have one of those tags"). هر قاعده جهت (INGRESS پیشفرض یا EGRESS)، allow یا deny و priority دارد: "an integer between 0 and 65535 ... The default value is 1000 ... Lower values indicate higher priority ... DENY rules take precedence over ALLOW rules if they have equal priority" و "VPC networks have implied rules with a priority of 65535". Source tagها "cannot be used to control traffic to an instance's external IP address". NSG در Azure به زیرشبکه یا NIC وصل میشود، priority قاعده "between 100 and 4096" است، اولین match پردازش را متوقف میکند، قاعدههای پیشفرض روی ۶۵۰۰۰، ۶۵۰۰۱ و ۶۵۵۰۰ هستند (allow VNet، allow load balancer، deny all ورودی؛ برای خروجی آینهای) و "Network security group rules only affect new connections". منبع میتواند service tag (مجموعهای از prefixها که مایکروسافت نگه میدارد) یا application security group (برچسب روی VMها) باشد.
| Property | AWS security group | AWS network ACL | GCP VPC firewall rule | Azure NSG | Kubernetes NetworkPolicy |
|---|---|---|---|---|---|
| Attached to | ENI (instance, LB, Lambda) | Subnet | VPC network, selecting by tag or service account | Subnet or NIC | Pods (by label) |
| Stateful | Yes | No | Yes (see note) | Yes | Yes |
| Allow / deny | Allow only | Allow and deny | Allow and deny | Allow and deny | Allow only |
| Rule order | None (all rules unioned) | Ascending rule number, first match | Priority 0-65535, lower first; deny wins ties | Priority 100-4096, lowest first | None (additive) |
| Default inbound | Deny | Default NACL allow all; custom NACL deny all | Implied deny (priority 65535) | Deny (65500) | Allow until selected |
| Default outbound | Allow all | Same as inbound | Implied allow (priority 65535) | Allow (65000-65500 defaults) | Allow until selected |
| References to other groups | SG IDs, prefix lists | CIDRs only | Tags, service accounts | Service tags, ASGs | Pod and namespace selectors |
| Changes affect existing flows | Not tracked ones | Yes immediately | Per cloud docs | No | CNI-defined |
| Logging | VPC Flow Logs | VPC Flow Logs | Firewall Rules Logging | Virtual network flow logs (NSG flow logs retire 2027-09-30) | CNI-specific (Hubble, Calico flow logs) |
| Cost | Free | Free | Free | Free | Free (CNI is the cost) |
یادداشت منبع: گزارههای GCP دربارهٔ priority، target tag و قاعدههای ضمنی از schema مربوط به Compute API گوگل (توضیح منبع Firewall، منتشرشده در مخزن googleapis) آمده؛ سایت مستندات گوگل از این ماشین جلوی fetch خودکار را میگیرد، پس حالتداری GCP و جهت قاعدههای ضمنی از دانش عمومی گفته شده نه از صفحهٔ fetchشده.
سناریوهای واقعی: برنامهٔ سهلایه (security group مربوط به ALB: 443 از همه؛ SG برنامه: 8080 فقط از SG مربوط به ALB؛ SG پایگاهداده: 5432 فقط از SG برنامه)؛ deny سراسری زیرشبکه برای یک CIDR بدخواه که security group نمیتواند بگوید؛ قاعدهٔ GCP «allow tcp:5432 from tag web to tag db»؛ NSG در Azure با service tag به نام Storage.
راهحل / نحوهٔ استفاده (Terraform و AWS CLI):
# a security group rule that references another group instead of an address
aws ec2 authorize-security-group-ingress --group-id sg-0db --protocol tcp --port 5432 --source-group sg-0app
# a NACL pair: allow HTTPS in, and the ephemeral range out
aws ec2 create-network-acl-entry --network-acl-id acl-0abc --ingress --rule-number 100 --protocol tcp --port-range From=443,To=443 --cidr-block 0.0.0.0/0 --rule-action allow
aws ec2 create-network-acl-entry --network-acl-id acl-0abc --egress --rule-number 100 --protocol tcp --port-range From=1024,To=65535 --cidr-block 0.0.0.0/0 --rule-action allowکنترل Egress (Egress control) مهم
به زبان ساده: قاعدههای ingress غریبهها را بیرون نگه میدارند؛ قاعدههای egress محدود میکنند سرورهای خودتان به کجا وصل شوند. سروری که فقط با سه مقصد حرف میزند نمیتواند دادهتان را به مقصد چهارم بفرستد.
بدفهمی رایج: «پشت فایروال هستیم، خروجی امن است.» پس از نفوذ، اولین حرکتهای مهاجم خروجی است: دانلود payload، باز کردن reverse shell، نشت داده (exfiltration)، تماس با سرور فرمان. egress پیشفرض-allow همهٔ اینها را ممکن میکند.
تعریف: کنترل egress یک allow-list روی اتصالهای خروجی است: بر پایهٔ CIDR مقصد و پورت یا نام دامنه. مورد زنجیرهٔ تأمین (Supply chain) واقعی است: build یا composer install، npm install، go get یا docker pull در زمان اجرا میتواند کدی از registryای اجرا کند که شما کنترلش نمیکنید؛ محدودکردن میزبانهای build و runtime به registryها و mirrorهای خودتان آنچه یک بستهٔ مخرب میتواند به آن برسد را کم میکند.
| Layer | How to restrict egress | Limit |
|---|---|---|
| Host | nftables output chain with policy drop and per-destination accepts (the Go generator below emits it) | IP-based; CDN addresses change |
| Docker | DOCKER-USER rules on -o ext_if, an internal network (docker network create --internal), a forward proxy container | Per host |
| Security group | Remove the default allow-all outbound rule, add specific ones | SG cannot filter by domain; cannot block DNS to the Route 53 Resolver |
| NACL | Subnet-wide outbound deny and allow list | Stateless: replies need return rules |
| Kubernetes | NetworkPolicy egress with ipBlock/selectors; Cilium toFQDNs (see the manifest below); egress gateways give pods a fixed source IP | Core NetworkPolicy has no DNS names |
| Cloud DNS-aware | AWS Network Firewall (domain allow-lists via stateful rule groups), Route 53 Resolver DNS Firewall, Azure Firewall FQDN rules, GCP Cloud NAT plus firewall policies | Paid service; inspection point |
| Proxy | Outbound HTTP(S) only through a proxy that enforces an allow-list (squid, Envoy) | Apps must honour HTTP_PROXY |
# Cilium extension (not core Kubernetes): allow egress by DNS name.
apiVersion: cilium.io/v2
kind: CiliumNetworkPolicy
metadata:
name: api-egress-fqdn
namespace: shop
spec:
endpointSelector:
matchLabels: { app: api }
egress:
- toEndpoints:
- matchLabels:
io.kubernetes.pod.namespace: kube-system
k8s-app: kube-dns
toPorts:
- ports: [{ port: "53", protocol: ANY }]
rules:
dns:
- matchPattern: "*" # lets Cilium see the lookups it must map to IPs
- toFQDNs:
- matchName: api.payments.example
- matchName: registry.npmjs.org
toPorts:
- ports: [{ port: "443", protocol: TCP }]NAT gateway بهاضافهٔ فیلتر دامنه. زیرشبکههای خصوصی از راه NAT gateway به اینترنت میرسند (به NAT در cloud نگاه کنید). NAT gateway هر چیزی را forward میکند؛ برای اجرای «فقط این دامنهها» فایروالی در مسیر میگذارید (AWS Network Firewall، پراکسی Squid یا Envoy، یا سرویس فایروال ارائهدهنده) تا route table ترافیک زیرشبکهٔ خصوصی را اول از نقطهٔ بازرسی بگذراند. Elastic IP ثابت روی NAT gateway هم یک آدرس به شرکا میدهد تا allow-list کنند.
Egress gatewayهای Kubernetes. گروهی از Podها از یک گره یا gateway مشخص از خوشه خارج میشوند تا مقصد یک IP مبدأ ثابت ببیند و یک نقطه سیاست egress را اعمال کند. Cilium به آن Egress Gateway میگوید؛ Calico هم egress gateway دارد؛ هر دو ویژگی CNIاند نه NetworkPolicy هستهٔ Kubernetes.
وقتی egress را سفت میکنید چه چیزهایی را مجاز بگذارید: DNS (فقط به resolver خودتان)، NTP، registryها یا mirrorهای بسته، ارائهدهندگان پرداخت و ایمیل، endpointهای observability، آدرس metadata ابری برای workloadهایی که لازم دارند، و ترافیک برگشت health check. پیش از اجرا یک هفته آنچه سیاست جدید drop میکند را لاگ کنید (قاعدهٔ log یا flow log).
سناریوهای واقعی: سرویس پرداختی که فقط دو CIDR و پایگاهداده را صدا میزند؛ CI runner که به mirror registry شما محدود است؛ Podای که فقط به api.payments.example:443 اجازه دارد.
فایروال میزبان روی سرورها در برابر محیط (Host firewalls vs the perimeter) مهم
به زبان ساده: فایروال محیطی (Perimeter؛ security group، دستگاه لبه، NACL) از چندین ماشین محافظت میکند؛ فایروال میزبان (Host firewall؛ nftables روی خود ماشین) از یک ماشین در برابر همهچیز محافظت میکند، از جمله همسایههایش.
بدفهمی رایج: «security group کافی است.» security group اینترنت را متوقف میکند. همسایهٔ نفوذشده در VPC، instance دیگری در همان گروه یا اشتباه در خود گروه را متوقف نمیکند. دفاع در عمق (Defense in depth) یعنی دو دیوار مستقل، تا یک قاعدهٔ غلط نفوذ نباشد.
| Aspect | Perimeter (SG, NACL, edge firewall) | Host firewall (nftables, ufw) |
|---|---|---|
| Managed by | Cloud API, Terraform, network team | Config management, image bake, the server owner |
| Sees | Traffic entering or leaving the instance or subnet | Everything incl. east-west and loopback |
| Survives a root compromise on the host | Yes | No: root can flush it |
| Central audit | Yes (flow logs) | Per host (counters, logs) |
| Per-process control | No | Yes: -m owner --uid-owner on OUTPUT |
| Typical failure | Too-broad CIDR such as 0.0.0.0/0 | Rules lost on reboot; Docker bypass |
از هر دو استفاده کنید: محیط برای مرزهای درشت و مرورشدهٔ مرکزی؛ میزبان برای «این سرویس این کلاینتها را میپذیرد» و برای محدودیتهای egress. قاعدههای میزبان را ماندگار کنید (nft list ruleset > /etc/nftables.conf، netfilter-persistent، firewall-cmd --permanent).
bind کردن listener برنامه: دیوار دوم (Application listener binding) مهم
به زبان ساده: اگر سرویسی فقط روی 127.0.0.1 گوش دهد، هیچ اشتباه فایروالی نمیتواند آن را به شبکه نشان دهد، چون سوکت روی اینترفیس شبکه وجود ندارد.
بدفهمی رایج: «localhost و 0.0.0.0 هر دو «محلی»اند.» 0.0.0.0 یعنی «همهٔ اینترفیسها» از جمله عمومی. 127.0.0.1 یعنی «فقط loopback».
تعریف: آدرسی که سرور به bind() میدهد تعیین میکند کدام اینترفیسها به آن میرسند. سرویس پشت reverse proxy روی همان میزبان باید روی loopback یا Unix socket گوش دهد؛ فقط proxy عمومی گوش میدهد. برای endpointهای ادمین، Unix socket با مجوزهای فایل خود پورت را حذف میکند (مثال Go).
$ ss -ltn # Local Address column
LISTEN 0 511 127.0.0.1:9000 0.0.0.0:* # php-fpm: only nginx on this host can reach it
LISTEN 0 511 0.0.0.0:80 0.0.0.0:* # nginx: public on purpose
LISTEN 0 128 0.0.0.0:6379 0.0.0.0:* # redis on every interface: one firewall mistake from a breach| Service | Where to set the bind address |
|---|---|
| PostgreSQL | listen_addresses = 'localhost' (default) or a private IP |
| MySQL / MariaDB | bind-address = 127.0.0.1 |
| Redis | bind 127.0.0.1 -::1, protected-mode yes |
| MongoDB | net.bindIp: 127.0.0.1 |
| nginx / php-fpm | listen 127.0.0.1:9000; or a Unix socket listen = /run/php/php-fpm.sock |
| Docker | -p 127.0.0.1:8080:80 |
| Laravel | php artisan serve --host=127.0.0.1; Octane --host=127.0.0.1 behind nginx |
| Go | http.Server{Addr: "127.0.0.1:8080"} instead of ":8080" |
| Kubernetes | Containers must listen on 0.0.0.0 inside the pod for Services to work; use NetworkPolicy to restrict |
WAF در برابر فایروال در برابر security group (WAF vs firewall vs security group) مهم
به زبان ساده: به لایههای متفاوت نگاه میکنند. security group و packet filter هدر میخوانند؛ WAF HTTP را میخواند.
بدفهمی رایج: «WAF جای فایروال را میگیرد» (یا برعکس). WAF هرگز پورتی را که terminate نمیکند نمیبیند؛ security group هرگز SQL injection نمیبیند. هرکدام چیزهایی را میبندد که دیگری نمیتواند.
| Control | Layer | Sees | Blocks | Does not stop |
|---|---|---|---|---|
| nftables / iptables | L3-L4 (conntrack adds state) | 5-tuple, flags, state | Unwanted ports and sources | SQL injection on an allowed port |
| AWS security group | L3-L4, stateful, per ENI | 5-tuple of new flows | Same, at the instance | Anything on an allowed port |
| AWS network ACL | L3-L4, stateless, per subnet | 5-tuple per packet | Subnet-wide CIDRs and ports | Application attacks |
| NetworkPolicy | L3-L4, per pod | Pod labels, CIDRs, ports | East-west traffic | Application attacks, anything L7 |
| Network firewall (AWS Network Firewall, NGFW) | L3-L7 inspection | Domain names (SNI), signatures | Exfiltration to unlisted domains | Encrypted payload content |
| L7 proxy / ingress / API gateway | L7 | HTTP method, path, headers | Unauthenticated routes, oversized bodies | Network-layer floods |
| WAF | L7 | Request content | SQLi, XSS patterns, bad bots, rate abuse | Direct access to a non-HTTP port |
| mTLS / service mesh | L4-L7 identity | Certificate identity | Callers without a valid identity | Compromised but valid services |
کاهش DDoS، طراحی قاعدهٔ WAF و کنترل bot در DDoS و امنیت شبکه است؛ mTLS در mTLS.
شکستهای رایج (Common failures)
| Symptom | Cause | How to confirm | Fix |
|---|---|---|---|
| Security group allows 443 but the page never loads (SYN reaches the instance, the SYN-ACK never arrives) | NACL outbound lacks the ephemeral range; stateless NACL drops the reply | VPC Flow Logs show ACCEPT inbound and REJECT for the return flow; compare NACL outbound rules | Add outbound allow tcp 1024-65535 (and inbound for the reverse case) |
Database port is public although ufw status says deny | Docker published it; DNAT sends it through FORWARD, not INPUT | docker ps shows 0.0.0.0:5432->5432; iptables -t nat -S DOCKER | Bind 127.0.0.1:5432:5432, or a DOCKER-USER drop matching --ctorigdstport 5432 |
| NetworkPolicy applied, traffic unchanged | CNI does not implement it, or the policy selects different labels | kubectl describe networkpolicy; check the CNI; labels on the pods | Use Calico/Cilium/Antrea/Kube-router; fix selectors |
| After default-deny egress, every pod fails with name errors | DNS not allowed | nslookup times out | Add the allow-DNS policy |
| Load balancer marks every target unhealthy | The target's SG or NACL blocks the health-check source (the LB's SG or subnet) | Target group health reason; SG inbound rules | Allow the LB SG (or its subnet) on the health-check port; NACL: the AWS docs warn that a deny for 0.0.0.0/0 or the subnet CIDR stops health checks |
| Small requests succeed, large uploads or TLS handshakes with big certificates hang | ICMP "fragmentation needed" or "packet too big" dropped: MTU black hole | ping -M do -s 1472 host fails at a size, tracepath, tcpdump icmp | Allow ICMP type 3 code 4 and ICMPv6 type 2; clamp MSS |
SSH worked, then died right after ufw enable or policy drop | Established rule missing or placed after the drop | Console access; nft list ruleset order | ct state established,related accept first; schedule an auto-revert |
| New connections fail under load, old ones work | conntrack table full | dmesg shows a conntrack "table full" message; conntrack -C | Raise nf_conntrack_max, shorten timeouts, notrack for known flows |
| IPv4 locked down, IPv6 open | No ip6tables/inet rules, or SG missing ::/0 | ss -ltn6, nmap -6 | Use an inet table, add IPv6 rules |
| Rules vanish after reboot | Not persisted | nft list ruleset is empty after boot | nftables.service with /etc/nftables.conf; netfilter-persistent |
iptables -L looks empty but traffic is still filtered | Rules live in nftables tables, another table, or another network namespace | nft list ruleset, iptables-nft -S, ip netns | List with the matching tool and namespace |
| Admin UI reachable from the internet | Service bound to 0.0.0.0 and SG too wide | ss -ltn, scan from outside | Bind to loopback or a Unix socket; narrow the SG |
| Webhook provider cannot reach you | Source IP not allowed by SG, or provider ranges changed | Flow logs; provider's published ranges | Allow the provider ranges from a managed list; verify signatures too |
ممیزی (Auditing)
| Question | Command | What to read |
|---|---|---|
| What rules exist, in nft form? | nft list ruleset | Tables, chains, hooks, priorities, policies; -a adds handles |
| What rules exist, in iptables form? | iptables -S, iptables-save | Replayable text; -t nat, -t raw, -t mangle for other tables |
| Which rule is actually matching? | iptables -L -n -v --line-numbers or nft list ruleset with counter | Packet and byte counters per rule |
| Live trace of one packet | nft monitor trace after meta nftrace set 1 on a match | Each rule the packet passes |
| What flows are tracked? | conntrack -L, conntrack -C, conntrack -S | State, NAT tuples, timeouts, insert_failed |
| What is listening? | ss -ltnup | Local address (loopback or all interfaces) and the process |
| What is reachable from outside? | nmap -sS -p- host from another network, nc -zv host port | Open vs filtered (timeout) vs closed (refused) |
| Which firewall is active? | ufw status verbose, firewall-cmd --list-all, systemctl status nftables | The front-end's view |
| What did the cloud allow or reject? | AWS VPC Flow Logs, GCP Firewall Rules Logging, Azure virtual network flow logs | ACCEPT/REJECT per 5-tuple |
| What does Kubernetes enforce? | kubectl get networkpolicy -A, kubectl describe networkpolicy, cilium monitor --type drop, calicoctl get networkpolicy | Policies, selectors, drops |
| Docker's rules | iptables -S DOCKER-USER, iptables -t nat -S DOCKER, docker network inspect | Published ports and your own rules |
رکورد AWS VPC Flow Logs خطی از فیلدهاست و جفت ACCEPT/REJECT میگوید NACL تصمیم گرفته یا SG. قالب پیشفرض version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status است:
2 123456789012 eni-0a1b2c3d 198.51.100.9 10.0.1.25 51344 443 6 12 4880 1700000000 1700000060 ACCEPT OK
2 123456789012 eni-0a1b2c3d 10.0.1.25 198.51.100.9 443 51344 6 10 9800 1700000000 1700000060 REJECT OKخط اول (درخواست) پذیرفته شده؛ دومی (پاسخ) رد شده: قاعدهٔ خروجی NACL کم است. «refused» در برابر «timeout» هم یک نشانه است: پورت بسته (listener نیست، فایروال اجازه میدهد) با RST جواب میدهد («connection refused»)، پورت فیلترشده (DROP) چیزی نمیدهد (timeout) و REJECT خطای سریع میدهد. راهنمای عیبیابی را ببینید.
سازوکار (Mechanics)
مجموعهقاعده چطور ارزیابی میشود. صفحهٔ man ابزار nft خلاصه میکند: برای هر hook "the attached chains are evaluated in order of their priorities"؛ "An accept verdict ... ends the evaluation of the current base chain ... The packet advances to the next base chain. Thus a packet is ultimately accepted if and only if no (matching) rule or base chain policy issues a drop verdict"؛ و "A drop verdict ... immediately ends the evaluation of the whole ruleset." نتیجه: دو table مستقل (مال شما و مال Docker، ufw و firewalld) روی یک hook هر دو رأی دارند و drop در هر جا برنده است. برای همین ACCEPT در Docker هرگز DROP شما را باطل نمیکند، ولی ACCEPT شما هم DROP Docker را باطل نمیکند. "Even if a packet is accepted by the ruleset it may still get discarded by other means, for example ... net.ipv4.conf.*.rp_filter."
| Verdict / statement | Effect | Note |
|---|---|---|
accept | Stops this base chain; next base chain at the same hook still runs | In iptables, ACCEPT in a built-in chain ends that chain's traversal for that table |
drop | Packet discarded, sender sees nothing | Final for the whole ruleset |
reject | Discards and sends ICMP unreachable or TCP RST | Faster failure; leaks that a host exists |
jump chain / goto chain | Evaluate a regular chain; jump returns, goto does not | Chains in other tables cannot be called |
return | Back to the calling chain | Policy applies at the end of a base chain |
log / counter / limit | Non-terminating statements | Place before the verdict |
dnat / snat / masquerade | NAT in the nat hooks, first packet of a flow only | Reply and later packets are translated by conntrack |
notrack | Skip conntrack for this packet (raw priority) | You must then match with stateless rules |
کارایی. iptables فهرست را خطی میپیماید: هزار قاعده یعنی هزار مقایسه برای هر جریان جدید. setهای nftables (hash، rbtree، interval) «آیا این آدرس در فهرست است» را به یک lookup تبدیل میکنند و ct state established بستههای بعدی را میانبر میزند، پس ترتیب «invalid، established، بعد موارد خاص» هم درست است هم سریع. Kubernetes با هزاران Service همان چیزی بود که kube-proxy را به IPVS، nftables و datapathهای eBPF کشاند. فایروالهای ابری سمت ارائهدهنده مقیاس میگیرند، اما سهمیه دارند (قاعده در هر گروه، گروه در هر interface، قاعدهٔ NACL در هر NACL).
رفتار هر محصول که غافلگیر میکند.
| Product | Behaviour |
|---|---|
Linux, iptables REJECT vs DROP | DROP hides a closed port (client times out, scanner learns nothing); REJECT is friendlier for internal clients and avoids long timeouts |
| Linux, loopback | Allow iifname "lo" or local services stop talking to each other (DNS stub, PHP-FPM over TCP) |
Linux, rp_filter | Reverse path filtering can drop asymmetric traffic regardless of your rules |
| Docker | Container-to-container on one user-defined bridge is allowed; published ports are DOCKER-chain rules; iptables: false breaks masquerading |
| AWS | SG changes apply instantly to new flows; tracked flows survive; NACL changes break flows immediately |
| GCP | Priority 0-65535; deny wins ties; implied rules at 65535 |
| Azure | Priority 100-4096; same-priority conflicts are not allowed; existing connections survive a rule removal |
| Kubernetes | Additive allow-only model; enforcement by CNI; NodePort or LB source IP may be rewritten before policy |
حل مسئلههای کلاسیک (Solving the classic problems)
| Problem | Solution | How | Cost / limitation |
|---|---|---|---|
| A server must expose only web and SSH | Default-deny host policy + security group | policy drop, established first, then tcp dport {80,443} and an admin set | Remote lockout risk while editing |
| Rules drift between hosts | Rules generated from one policy file | The Go generator below, Terraform, Ansible | A generator is code you must test |
| A container's published port is public | Bind to loopback, or DOCKER-USER filter | -p 127.0.0.1:..., --ctorigdstport rules | Per host; nftables backend needs its own table |
| Namespace has no isolation | Default-deny + allow-DNS + explicit allows | NetworkPolicy templates per namespace | Needs an enforcing CNI |
| Return traffic blocked in a subnet | Ephemeral return rule on the NACL, or no custom NACL | Outbound allow tcp 1024-65535 | Wide port range, a coarse control |
| Brute force on SSH | Per-source rate limit, key-only auth, VPN or bastion | nft meter, fail2ban, VPN | Shared NAT addresses get caught together |
| Admin UI must not face the internet | Unix socket or loopback listener + CIDR middleware | Go example below, Laravel middleware | Admin tools must run on or tunnel to the host |
| Exfiltration after a compromise | Egress allow-list | output chain policy drop, NetworkPolicy egress, FQDN firewall | Maintenance of allowed destinations |
| Webhook from a provider | Source CIDR allow-list plus signature | allow.cidr middleware, HMAC check | Provider ranges change |
| Big uploads hang | Allow ICMP errors, clamp MSS | Rules above | None worth mentioning |
بررسیگر سیاست و مولد nftables در Go (A policy checker and nftables generator in Go)
هدف: یک فایل YAML کوچک جریانهایی را فهرست میکند که یک میزبان اجازه میدهد («allowed flows»)، برنامه آن را اعتبارسنجی میکند و مجموعهقاعدهٔ nftables را چاپ میکند که بقیه را رد میکند. چیزهایی را رد میکند که بیصدا قاعدهٔ غلط میسازند (CIDR بد، پروتکل ناشناخته، پورت جاافتاده)، همتاهای IPv4 و IPv6 را در یک table از نوع inet به قاعدههای جدا میشکند، قاعدههای established، invalid، ICMP و محافظ ping آزمایشگاه را مینویسد و فهرست egress: را به chain output با policy drop تبدیل میکند. مولد آموزشی است: زیرمجموعهٔ YAML با دست parse میشود تا ماژول بدون وابستگی بماند؛ برای کار واقعی gopkg.in/yaml.v3 را بگیرید.
فایل سیاست:
# Allowed flows for one host. Anything not listed is dropped.
name: web
ingress:
- name: public-web
from: [any]
proto: tcp
ports: [80, 443]
- name: admin-ssh
from: [10.0.0.0/8, 192.0.2.0/24, "2001:db8:100::/48"]
proto: tcp
ports: [22]
- name: metrics
from: [10.1.0.0/16]
proto: tcp
ports: [9100]
egress:
- name: postgres
to: [10.2.0.0/24]
proto: tcp
ports: [5432]
- name: dns
to: [10.0.0.2/32]
proto: udp
ports: [53]
- name: https-out
to: [203.0.113.0/24]
proto: tcp
ports: [443]برنامه:
// policygen reads a YAML list of allowed flows and prints an nftables ruleset
// that denies everything else. It uses only the standard library plus a tiny
// parser for the fixed YAML shape shown in policy.yaml.
package main
import (
"bufio"
"fmt"
"io"
"net/netip"
"os"
"sort"
"strconv"
"strings"
)
// Flow is one allowed (direction-less) flow: who, which protocol, which ports.
type Flow struct {
Name string
Peers []string // CIDRs or "any"
Proto string // tcp or udp
Ports []uint16
}
// Policy holds the ingress and egress allow-lists of one host.
type Policy struct {
Name string
Ingress []Flow
Egress []Flow
}
// Parse reads the restricted YAML subset: top-level name, ingress, egress;
// list items start with "- name:", other keys are from/to, proto, ports.
func Parse(r io.Reader) (*Policy, error) {
p := &Policy{}
var section *[]Flow
var cur *Flow
sc := bufio.NewScanner(r)
for n := 1; sc.Scan(); n++ {
line := strings.TrimRight(sc.Text(), " \t")
if i := strings.Index(line, "#"); i >= 0 {
line = strings.TrimRight(line[:i], " \t")
}
if strings.TrimSpace(line) == "" {
continue
}
trim := strings.TrimSpace(line)
switch {
case strings.HasPrefix(line, "name:"):
p.Name = strings.TrimSpace(strings.TrimPrefix(line, "name:"))
case line == "ingress:":
section = &p.Ingress
case line == "egress:":
section = &p.Egress
case strings.HasPrefix(trim, "- name:"):
if section == nil {
return nil, fmt.Errorf("line %d: flow outside ingress/egress", n)
}
*section = append(*section, Flow{Name: strings.TrimSpace(strings.TrimPrefix(trim, "- name:"))})
cur = &(*section)[len(*section)-1]
case cur != nil:
key, val, ok := strings.Cut(trim, ":")
if !ok {
return nil, fmt.Errorf("line %d: expected key: value", n)
}
val = strings.TrimSpace(val)
switch key {
case "from", "to":
cur.Peers = splitList(val)
case "proto":
cur.Proto = val
case "ports":
for _, s := range splitList(val) {
v, err := strconv.ParseUint(s, 10, 16)
if err != nil || v == 0 {
return nil, fmt.Errorf("line %d: bad port %q", n, s)
}
cur.Ports = append(cur.Ports, uint16(v))
}
default:
return nil, fmt.Errorf("line %d: unknown key %q", n, key)
}
default:
return nil, fmt.Errorf("line %d: unexpected %q", n, trim)
}
}
return p, sc.Err()
}
func splitList(v string) []string {
v = strings.Trim(v, "[]")
var out []string
for _, s := range strings.Split(v, ",") {
if s = strings.Trim(strings.TrimSpace(s), "\"'"); s != "" {
out = append(out, s)
}
}
return out
}
// Validate rejects anything that would silently produce a wrong rule.
func (p *Policy) Validate() error {
for _, f := range append(append([]Flow{}, p.Ingress...), p.Egress...) {
if f.Proto != "tcp" && f.Proto != "udp" {
return fmt.Errorf("flow %q: proto must be tcp or udp, got %q", f.Name, f.Proto)
}
if len(f.Ports) == 0 || len(f.Peers) == 0 {
return fmt.Errorf("flow %q: ports and peers are required", f.Name)
}
for _, peer := range f.Peers {
if peer == "any" {
continue
}
if _, err := netip.ParsePrefix(peer); err != nil {
return fmt.Errorf("flow %q: bad CIDR %q: %w", f.Name, peer, err)
}
}
}
return nil
}
// split separates peers into IPv4 prefixes, IPv6 prefixes and the "any" flag.
func split(peers []string) (v4, v6 []string, any bool) {
for _, peer := range peers {
if peer == "any" {
any = true
continue
}
pf := netip.MustParsePrefix(peer)
if pf.Addr().Is4() {
v4 = append(v4, pf.String())
} else {
v6 = append(v6, pf.String())
}
}
return
}
func portSet(ports []uint16) string {
sorted := append([]uint16(nil), ports...)
sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
s := make([]string, len(sorted))
for i, p := range sorted {
s[i] = strconv.Itoa(int(p))
}
return "{ " + strings.Join(s, ", ") + " }"
}
// rules renders one chain body. dir is "saddr" for ingress and "daddr" for egress.
func rules(flows []Flow, dir, portKey string) []string {
var out []string
for _, f := range flows {
v4, v6, any := split(f.Peers)
ports := portSet(f.Ports)
out = append(out, "# "+f.Name)
if any {
out = append(out, fmt.Sprintf("%s %s %s ct state new accept", f.Proto, portKey, ports))
}
if len(v4) > 0 {
out = append(out, fmt.Sprintf("ip %s { %s } %s %s %s ct state new accept", dir, strings.Join(v4, ", "), f.Proto, portKey, ports))
}
if len(v6) > 0 {
out = append(out, fmt.Sprintf("ip6 %s { %s } %s %s %s ct state new accept", dir, strings.Join(v6, ", "), f.Proto, portKey, ports))
}
}
return out
}
// Render produces the full nftables script.
func (p *Policy) Render() string {
var b strings.Builder
w := func(format string, a ...any) { fmt.Fprintf(&b, format+"\n", a...) }
w("#!/usr/sbin/nft -f")
w("# generated from policy %q; do not edit by hand", p.Name)
w("flush ruleset")
w("table inet filter {")
w("\tchain input {")
w("\t\ttype filter hook input priority filter; policy drop;")
w("\t\tct state invalid drop")
// The ping limiter must precede "established": later echo requests of a flow count as established.
w("\t\tip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop")
w("\t\tmeta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop")
w("\t\tct state established,related accept")
w("\t\tiifname \"lo\" accept")
w("\t\tip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem, echo-request } accept")
w("\t\tmeta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert, echo-request } accept")
for _, r := range rules(p.Ingress, "saddr", "dport") {
w("\t\t%s", r)
}
w("\t\tlimit rate 5/minute burst 5 packets log prefix \"%s-in-drop: \" counter", p.Name)
w("\t}")
w("\tchain forward {")
w("\t\ttype filter hook forward priority filter; policy drop;")
w("\t}")
w("\tchain output {")
if len(p.Egress) == 0 {
w("\t\ttype filter hook output priority filter; policy accept;")
} else {
w("\t\ttype filter hook output priority filter; policy drop;")
w("\t\tct state established,related accept")
w("\t\toifname \"lo\" accept")
w("\t\tip protocol icmp accept")
w("\t\tmeta l4proto ipv6-icmp accept")
for _, r := range rules(p.Egress, "daddr", "dport") {
w("\t\t%s", r)
}
w("\t\tlimit rate 5/minute burst 5 packets log prefix \"%s-out-drop: \" counter", p.Name)
}
w("\t}")
w("}")
return b.String()
}
func main() {
in := io.Reader(os.Stdin)
if len(os.Args) > 1 {
f, err := os.Open(os.Args[1])
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(2)
}
defer f.Close()
in = f
}
p, err := Parse(in)
if err == nil {
err = p.Validate()
}
if err != nil {
fmt.Fprintln(os.Stderr, "policy error:", err)
os.Exit(1)
}
fmt.Print(p.Render())
}اجرای واقعی، سپس بررسی نحو با nft -c (فقط بررسی، چیزی بارگذاری نمیکند) و آزمون زندهٔ سیاست egress در یک کانتینر: پیش از بارگذاری، اتصال TCP به 1.1.1.1:80 موفق است؛ پس از بارگذاری مجموعهقاعدهٔ تولیدشده (egress با default-drop، 1.1.1.1 در فهرست نیست) timeout میشود؛ شمارندهٔ drop بالا میرود:
$ go run ./policygen policygen/policy.yaml > web.nft
$ nft -c -f web.nft && echo SYNTAX-OK
SYNTAX-OK
$ nc -z -w3 1.1.1.1 80; echo "before: rc=$?"
Connection to 1.1.1.1 80 port [tcp/http] succeeded!
before: rc=0
$ nft -f web.nft && nc -z -w3 1.1.1.1 80; echo "after (egress default-drop): rc=$?"
after (egress default-drop): rc=1
$ nft list chain inet filter output | tail -4
ip daddr 10.0.0.2 udp dport 53 ct state new accept
ip daddr 203.0.113.0/24 tcp dport 443 ct state new accept
limit rate 5/minute burst 5 packets log prefix "web-out-drop: " counter packets 3 bytes 180
}chain input تولیدشده (ابتدای آن)، با دو جزئیاتی که مهماند: محدودکنندهٔ ping پیش از قاعدهٔ established است و همتاهای IPv4 و IPv6 قاعدههای جدا هستند:
chain input {
type filter hook input priority filter; policy drop;
ct state invalid drop
ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
meta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop
ct state established,related accept
iifname "lo" accept
...
# public-web
tcp dport { 80, 443 } ct state new accept
# admin-ssh
ip saddr { 10.0.0.0/8, 192.0.2.0/24 } tcp dport { 22 } ct state new accept
ip6 saddr { 2001:db8:100::/48 } tcp dport { 22 } ct state new acceptقاعدههای IPv6 فقط از نظر نحو بررسی شدند؛ شبکهٔ آزمایشگاه فقط IPv4 است.
listener ادمین بدون پورت برای فایروال: Unix socket (An admin listener with no port to firewall)
endpoint ادمین یا دیباگ (متریک، pprof، فرمان «drain») اصلاً به پورت TCP نیاز ندارد. Unix domain socket یک فایل است؛ اینکه چه کسی میتواند وصل شود با مجوز فایل تعیین میشود، پس چیزی برای اسکنر پیدا کردن نیست و چیزی نیست که فایروال فراموشش کند. این جایگزین «بدون port-knock» است: بهجای پنهانکردن پورت ادمین پشت توالی knock، پورت را حذف کنید.
// unixadmin serves the public API on TCP and the admin API ONLY on a Unix
// socket. There is no admin port to firewall, scan or forget to firewall:
// access is decided by file permissions on the socket (and its directory).
package main
import (
"errors"
"fmt"
"log"
"net"
"net/http"
"os"
"path/filepath"
"syscall"
"time"
)
func listenUnix(path string) (net.Listener, error) {
if err := os.MkdirAll(filepath.Dir(path), 0o750); err != nil {
return nil, err
}
// A stale socket file from a crashed run makes Listen fail with EADDRINUSE.
if err := os.Remove(path); err != nil && !errors.Is(err, os.ErrNotExist) {
return nil, err
}
// Create the socket with mode 0600 from the first instant (no chmod race).
old := syscall.Umask(0o177)
defer syscall.Umask(old)
return net.Listen("unix", path)
}
func main() {
public := http.NewServeMux()
public.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintln(w, "public ok")
})
public.HandleFunc("/admin/", http.NotFound) // never served here
admin := http.NewServeMux()
admin.HandleFunc("/admin/status", func(w http.ResponseWriter, r *http.Request) {
fmt.Fprintf(w, "admin ok, pid %d, time %s\n", os.Getpid(), time.Now().Format(time.RFC3339))
})
sock := "/tmp/unixadmin/admin.sock"
if len(os.Args) > 1 {
sock = os.Args[1]
}
ln, err := listenUnix(sock)
if err != nil {
log.Fatal(err)
}
go func() { log.Fatal((&http.Server{Handler: admin, ReadHeaderTimeout: 5 * time.Second}).Serve(ln)) }()
// Bind the public listener explicitly: 127.0.0.1 behind a reverse proxy,
// 0.0.0.0 only when something must reach it directly.
log.Println("public on 127.0.0.1:8080, admin on", sock)
log.Fatal((&http.Server{Addr: "127.0.0.1:8080", Handler: public, ReadHeaderTimeout: 5 * time.Second}).ListenAndServe())
}اجرای واقعی روی macOS (mode سوکت srw------- است، فقط مالک؛ listener عمومی برای /admin/ پاسخ 404 میدهد):
$ go build -o unixadmin ./unixadmin && ./unixadmin /tmp/uatest/admin.sock &
2026/11/25 21:15:50 public on 127.0.0.1:8080, admin on /tmp/uatest/admin.sock
$ ls -l /tmp/uatest/
srw-------@ 1 m.negahi wheel 0 Nov 25 21:15 admin.sock
$ curl -s --unix-socket /tmp/uatest/admin.sock http://x/admin/status
admin ok, pid 24143, time 2026-11-25T21:15:50+03:30
$ curl -s -o /dev/null -w "public /admin -> %{http_code}\n" http://127.0.0.1:8080/admin/status
public /admin -> 404| Detail | Why it matters |
|---|---|
syscall.Umask(0o177) around Listen | The socket is created 0600 from the start; chmod after Listen leaves a window |
| Removing a stale socket first | A crashed run leaves the file; Listen would fail with "address already in use" |
Directory mode 0750 | The directory is a second permission check |
Public server on 127.0.0.1:8080 | A reverse proxy on the host is the only public listener |
| Reaching it remotely | ssh -L can forward a local port to a remote Unix socket (-L 9090:/run/app/admin.sock); see VPNs and tunnels |
| Containers | Mount the socket with a volume; in Kubernetes use a shared emptyDir between sidecars |
allow-list در پایگاهداده (SQL) (Allow-lists in the database)
وقتی allow-list داده است (بازههای ادمین، بازههای webhook شریک، محدودیت IP مشتری) آن را در PostgreSQL با نوع cidr نگه دارید و عضویت را با عملگر <<= (شامل یا مساوی) بسنجید. همین تکنیک flow logها را هم match میکند. اجرای واقعی روی PostgreSQL 16:
CREATE TABLE firewall_allowlist (
id bigserial PRIMARY KEY,
list_name text NOT NULL,
cidr cidr NOT NULL,
note text,
expires_at timestamptz,
UNIQUE (list_name, cidr)
);
INSERT INTO firewall_allowlist (list_name, cidr, note) VALUES
('admin', '10.0.0.0/8', 'office VPN'),
('admin', '2001:db8:100::/48', 'office IPv6'),
('webhook:payments', '203.0.113.0/24', 'provider published range');
-- is this client allowed? (false for 198.51.100.9)
SELECT EXISTS (SELECT 1 FROM firewall_allowlist
WHERE list_name = 'admin' AND inet '198.51.100.9' <<= cidr
AND (expires_at IS NULL OR expires_at > now())) AS allowed;
-- allowed
-- ---------
-- f
-- which ports are rejected most? (flow-log table loaded from VPC Flow Logs)
SELECT dstport, count(*) AS rejects, count(DISTINCT srcaddr) AS sources
FROM flow_log
WHERE action = 'REJECT' AND start_time > now() - interval '1 hour'
GROUP BY dstport ORDER BY rejects DESC;
-- dstport | rejects | sources
-- 5432 | 2 | 2 <- a scanner hitting the database port
-- 51344 | 1 | 1 <- a reply rejected on an ephemeral port: the NACL bug
-- the NACL signature: a request ACCEPTed and its mirrored reply REJECTed
SELECT a.srcaddr, a.srcport, a.dstport
FROM flow_log a
JOIN flow_log b ON b.srcaddr = a.dstaddr AND b.dstaddr = a.srcaddr
AND b.srcport = a.dstport AND b.dstport = a.srcport
WHERE a.action = 'ACCEPT' AND b.action = 'REJECT';Laravel و PHP: دیوار دوم در سطح برنامه (Laravel and PHP: the application-level second wall)
Laravel نباید تنها چیز میان غریبه و /admin باشد، ولی باید خودش هم یک دیوار باشد. دو قاعده: بررسی از آدرس واقعی کلاینت استفاده کند (TrustProxies درست پیکربندی شده) و پیشفرضش deny باشد.
اول TrustProxies، چون هر بررسی IP به آن وابسته است. مستندات Laravel: "you may enable the Illuminate\Http\Middleware\TrustProxies middleware that is included in your Laravel application ... Your trusted proxies should be specified using the trustProxies middleware method in your application's bootstrap/app.php file". CIDR load balancer را trust کنید، هرگز * را روی میزبانی که هر کسی مستقیم میرسد: با * هر کلاینتی میتواند X-Forwarded-For: 10.4.5.6 بفرستد و مثل آدرس دفتر رفتار شود. دربارهٔ همین موضوع با NAT به NAT و port forwarding نگاه کنید.
<?php
use App\Http\Middleware\AllowFromCidr;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
// Trust ONLY the load balancer's subnet (the same CIDR your security group
// allows on port 80/443 from the LB). Never '*' on a host that is reachable directly.
$middleware->trustProxies(
at: ['10.20.0.0/24'],
headers: Request::HEADER_X_FORWARDED_FOR
| Request::HEADER_X_FORWARDED_HOST
| Request::HEADER_X_FORWARDED_PORT
| Request::HEADER_X_FORWARDED_PROTO,
);
$middleware->alias(['allow.cidr' => AllowFromCidr::class]);
})
->withExceptions(function (Exceptions $exceptions): void {
//
})->create();allow-listها بهصورت پیکربندی (تا staging و production فرق کنند):
<?php
// config/firewall.php
// Application-level allow-lists. They are the SECOND wall: the first one is
// the security group / nftables rule that already keeps strangers away.
return [
// Who may open /admin/*. Read from the environment so staging and prod differ.
'admin_cidrs' => array_filter(explode(',', (string) env('ADMIN_CIDRS', '10.0.0.0/8,127.0.0.1/32,::1/128'))),
// Providers that call our webhooks, with the source ranges they publish.
// Keep these in config/DB and refresh them: providers change ranges.
'webhook_sources' => [
'payments' => array_filter(explode(',', (string) env('PAYMENTS_WEBHOOK_CIDRS', '203.0.113.0/24,2001:db8:beef::/48'))),
],
];middleware. Symfony\Component\HttpFoundation\IpUtils::checkIp (request در Laravel یک Symfony request است) یک آدرس یا فهرست را میپذیرد، IPv4 و IPv6، با نمادگذاری CIDR. 404 برمیگرداند نه 403 تا اسکنر نتواند «صفحهای نیست» را از «ممنوع» تشخیص دهد:
<?php
declare(strict_types=1);
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\IpUtils;
use Symfony\Component\HttpFoundation\Response;
/**
* Deny by default: the request is served only when the client address is inside one of
* the CIDR blocks of the named list in config/firewall.php.
*
* Usage: Route::middleware('allow.cidr:admin_cidrs') or 'allow.cidr:webhook_sources.payments'.
*
* $request->ip() is only the real client when TrustProxies is configured for
* YOUR proxies; with 'at' => '*' anybody can spoof X-Forwarded-For and walk through.
*/
final class AllowFromCidr
{
public function handle(Request $request, Closure $next, string $list): Response
{
$allowed = (array) config('firewall.'.$list, []);
$ip = $request->ip();
if ($ip === null || $allowed === [] || ! IpUtils::checkIp($ip, $allowed)) {
// 404 (not 403) tells a scanner nothing about what exists here.
logger()->warning('firewall.app_denied', [
'list' => $list,
'ip' => $ip,
'remote_addr' => $request->server('REMOTE_ADDR'),
'path' => $request->path(),
]);
abort(404);
}
return $next($request);
}
}استفاده روی routeهای ادمین و route مربوط به webhook، با امضا بهعنوان اثبات واقعی:
<?php
// routes/web.php and routes/api.php (excerpt)
use App\Http\Controllers\Admin\DashboardController;
use App\Http\Controllers\PaymentWebhookController;
use Illuminate\Support\Facades\Route;
// Admin: network allow-list first, then authentication, then authorization.
Route::middleware(['allow.cidr:admin_cidrs', 'auth', 'can:view-admin'])
->prefix('admin')
->group(function (): void {
Route::get('/', [DashboardController::class, 'index']);
});
// Webhook: source IP is a cheap pre-filter; the HMAC signature in the
// controller is the real proof (IPs are shared, ranges change, headers can lie).
Route::post('/webhooks/payments', PaymentWebhookController::class)
->middleware('allow.cidr:webhook_sources.payments'); // in routes/api.php: no session, no CSRF<?php
declare(strict_types=1);
namespace App\Http\Controllers;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
final class PaymentWebhookController extends Controller
{
public function __invoke(Request $request): JsonResponse
{
// Defence in depth: the network layer let this packet in, now prove the sender knows the secret.
$expected = hash_hmac('sha256', $request->getContent(), (string) config('services.payments.webhook_secret'));
$given = (string) $request->header('X-Signature', '');
if (! hash_equals($expected, $given)) {
abort(401);
}
// ... enqueue the event; answer fast so the provider does not retry.
return response()->json(['ok' => true], 202);
}
}یک feature test که حالت جعل را هم دارد. تست سوم مهمترین است: وقتی هیچ proxy قابلاعتمادی پیکربندی نشده، X-Forwarded-For جعلی نادیده گرفته میشود:
<?php
declare(strict_types=1);
namespace Tests\Feature;
use Illuminate\Support\Facades\Route;
use Tests\TestCase;
final class AllowFromCidrTest extends TestCase
{
protected function setUp(): void
{
parent::setUp();
config(['firewall.admin_cidrs' => ['10.0.0.0/8', '2001:db8:100::/48']]);
Route::middleware('allow.cidr:admin_cidrs')->get('/admin-ping', fn () => 'pong');
}
public function test_inside_the_range_is_served(): void
{
$this->withServerVariables(['REMOTE_ADDR' => '10.4.5.6'])->get('/admin-ping')->assertOk();
$this->withServerVariables(['REMOTE_ADDR' => '2001:db8:100::7'])->get('/admin-ping')->assertOk();
}
public function test_outside_the_range_is_hidden(): void
{
$this->withServerVariables(['REMOTE_ADDR' => '198.51.100.9'])->get('/admin-ping')->assertNotFound();
}
public function test_spoofed_forwarded_for_is_ignored_without_a_trusted_proxy(): void
{
// The peer is a stranger; the header claims to be an admin. trustProxies does not trust the peer.
$this->withServerVariables(['REMOTE_ADDR' => '198.51.100.9'])
->withHeaders(['X-Forwarded-For' => '10.4.5.6'])
->get('/admin-ping')
->assertNotFound();
}
}| Piece | Why |
|---|---|
$middleware->trustProxies(at: ['10.20.0.0/24'], headers: ...) | Only the load balancer's subnet may set X-Forwarded-*; matches the SG rule that allows only the LB to reach port 80 |
Request::ip() | The client address after proxy resolution; REMOTE_ADDR is the peer (the proxy) |
IpUtils::checkIp($ip, $cidrs) | CIDR matching for both families; no regex, no ip2long bugs |
Middleware order allow.cidr then auth then can | Network, identity, permission: three independent checks |
abort(404) and a warning log | Hides the route and leaves an audit trail with REMOTE_ADDR |
Webhook IP allow-list plus hash_equals on an HMAC | IP ranges are shared and change; the signature proves possession of the secret |
Config from .env | ADMIN_CIDRS differs per environment; no code change to rotate ranges |
تلههایی که مال شبکهاند نه فریمورک: پشت Cloudflare، peer یک آدرس Cloudflare است و IP کلاینت در headerای است که فقط Cloudflare میتواند بگذارد (ترافیک origin را در security group به بازههای Cloudflare محدود کنید، بعد آنها را trust کنید)؛ پشت Service از نوع NodePort یا LoadBalancer در Kubernetes با externalTrafficPolicy: Cluster مبدأ به یک گره SNAT میشود (از Local یا PROXY protocol استفاده کنید)؛ CGNAT یعنی یک IPv4 میتواند چند نفر باشد، پس allow-list بر پایهٔ IP یک مرز است نه یک هویت (authorization و zero trust).
انتخاب (Choosing)
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One VPS running nginx, PHP, Postgres | nftables (or ufw) default-deny: 80, 443, SSH from your IP | Bind Postgres and PHP-FPM to loopback or a socket; fail2ban | Two walls: firewall and listener |
| Cloud web app | Security groups per tier referencing each other; default NACL | Flow logs; no 0.0.0.0/0 except the LB's 443 | Least privilege without address bookkeeping |
| Need to block a hostile CIDR subnet-wide | Custom NACL deny rule with a low number | Return-port rules; WAF for L7 | SGs cannot deny |
| Docker host with Compose | 127.0.0.1: publishes + a reverse proxy | DOCKER-USER rules, cloud SG | ufw does not see published ports |
| Kubernetes multi-tenant | Default-deny + allow-DNS per namespace | Calico/Cilium for logging, FQDN, global policy | Core NetworkPolicy is allow-only and namespaced |
| Locking down egress for a payments service | Egress allow-list by CIDR; FQDN with Cilium or a firewall service | NAT gateway with a fixed IP, domain filtering | Limits exfiltration and supply-chain callbacks |
| Public admin tool | Do not expose it: VPN, bastion, SSH tunnel, Unix socket | CIDR middleware as a backstop | A closed port cannot be attacked |
| Webhook receiver | Public endpoint, signature verification | Provider CIDR allow-list from a managed list | IPs are not identity |
| Home router with IPv6 | Stateful inbound-deny firewall | Allow specific services only | No NAT, so no accidental protection |
| Very large blocklists or many rules | nftables sets or ipset, or eBPF | Reload atomically from files | Linear iptables chains do not scale |
| Compliance and audit | Flow logs plus change-managed rules in Git | Terraform plan review | Proves what was allowed |
در معماری: از یک پردازه تا سیستم توزیعشده (In architecture: from a single process to a distributed system)
مونولیت (Monolith: یک پردازه، یک پایگاهداده)
مثال. یک VPS با Laravel (nginx بهاضافهٔ PHP-FPM) و PostgreSQL. فایروال ارائهدهنده ۸۰ و ۴۴۳ را از همه و ۲۲ را از IP دفتر اجازه میدهد. میزبان فایل nftables این فصل را اجرا میکند (default-deny، established، خطاهای ICMP، tcp dport {80,443}، set به نام admin_v4 برای SSH). PHP-FPM روی Unix socket و PostgreSQL روی localhost گوش میدهد. اسکن پورت از بیرون دو پورت باز و هیچ چیز دیگر میبیند؛ .env لو رفته با رمز پایگاهداده از اینترنت بیفایده است چون ۵۴۳۲ در دسترس نیست. routeهای ادمین از middleware به نام allow.cidr هم میگذرند.
مونولیت ماژولار (Modular monolith)
مثال. یک واحد deploy، چند ماژول (billing، catalogue، reporting)، دو پایگاهداده (OLTP و replica گزارش) روی میزبانهای جدا در زیرشبکههای خصوصی. security groupها لایهها را نام میبرند نه آدرسها: app-sg پورت ۴۴۳ را از alb-sg میپذیرد؛ db-sg پورت ۵۴۳۲ را فقط از app-sg؛ reporting-sg پورت ۵۴۳۲ را از SG میزبان گزارش. ماژولی که ناگهان به پایگاهداده دیگر نیاز پیدا کند fail-closed میشود و گفتوگو را اجباری میکند. Egress: SG برنامه ۴۴۳ به CIDRهای پرداخت و ایمیل و DNS را اجازه میدهد؛ بقیه drop. NACLها روی پیشفرض میمانند تا روز اول فقط یک لایه دیباگ شود.
میکروسرویسها (Microservices)
مثال. پانزده سرویس در یک خوشهٔ Kubernetes، یک namespace بهازای هر تیم. هر namespace همان سه سیاست را از الگو میگیرد: default-deny، allow-DNS، allow-from-ingress برای سرویسهایی که route دارند. سرویس سفارش میتواند inventory و payments را صدا بزند؛ payments فقط به CIDRهای ارائهدهنده و پایگاهدادهٔ خودش بیرون میرود. سرویس جدید بدون دسترسی شروع میکند و pull requestی که سیاست اضافه میکند همان طراحیمرور است («چه کسی این را صدا میزند؟»). Calico یا Cilium اجرا و flow log میدهد؛ تیم پلتفرم قاعدهٔ Cilium toFQDNs برای APIهای SaaS اضافه میکند. NetworkPolicy پاسخ میدهد «کدام Podها میتوانند وصل شوند»؛ mTLS پاسخ میدهد «چه کسی صدا میزند». هر دو لازماند چون labelهای Pod هویتهایی نیستند که از خوشه عبور کنند و Pod نفوذشده با label مجاز همچنان وصل میشود.
داده توزیعشده: replicaها، کش، چندمنطقهای (Distributed data: replicas, caches, multi-region)
مثال. یک primary در منطقهٔ A، replicaها و یک Redis cluster در منطقهٔ B روی VPN یا peering. security groupها پورت replication (۵۴۳۲، ۶۳۷۹ و ۱۶۳۷۹ برای bus خوشه) را فقط میان SGهای لایهٔ داده دو منطقه اجازه میدهند؛ CIDRهای منطقهٔ همتا در یک prefix list مدیریتشدهاند تا تغییر route یک ویرایش باشد. NACL در زیرشبکهٔ داده همهچیز را رد میکند جز CIDR همتا و لایهٔ برنامه و قاعدههای صریح پورت ephemeral برای پاسخهای replication دارد. لینکهای بینمنطقهای اغلب MTU کوچکتری دارند (encapsulation در VPN): replication روی batchهای بزرگ COPY گیر میکند تا وقتی ICMP «fragmentation needed» اجازه داده شود یا MSS clamp شود. failover نباید به قاعدهای وابسته باشد که کسی دستی ویرایش میکند: قاعدههای منطقهٔ آمادهبهکار از همان ماژول Terraform اعمال میشود و با تستی که از هر لایه nc -z اجرا میکند راستیآزمایی میشود.
مسیر مقیاس (Scaling path)
| Load / size | What breaks first | What to change |
|---|---|---|
| 1 server, 1x | Docker publishes a database, or 0.0.0.0 listeners | Loopback binds, default-deny, one reviewed ruleset |
| 10 servers, 10x | Rule drift; hand-edited security groups | Generate rules from one policy file or Terraform module; prefix lists; flow logs on |
| 100 services, 100x | Address-based rules do not map to pods that move | NetworkPolicy by label, CNI with identity (Cilium), SG references, default-deny templates |
| Thousands of rules or nodes | Linear iptables chains slow connection setup; conntrack tables fill | nftables sets, eBPF datapath, kube-proxy in IPVS or nftables mode, notrack where safe |
| Multi-region, many accounts | Inconsistent baselines, shadow rules | Central firewall policy (AWS Firewall Manager, GCP hierarchical policies, Azure Firewall Manager), org-level guardrails, automated drift detection |
| Zero trust target | IP allow-lists lag behind reality | Identity-based access (mTLS, workload identity, ZTNA) with network rules as the coarse outer wall |
آزمایشگاه (Lab)
هر آنچه پایین است روی همین ماشین در کانتینرهای Docker با --cap-add NET_ADMIN اجرا شد (قابلیت CAP_NET_ADMIN به کانتینر اجازه میدهد قاعدههای network namespace خودش را ویرایش کند)، هرکدام در network namespace جدا، پس چیزی به میزبان دست نمیزند. بخش ۳ یک daemon از نوع Docker-in-Docker (docker:dind، Docker 29.10، --privileged) به کار برد تا قاعدههای فایروال خود Docker امن تغییر کنند. بخش NetworkPolicy (۵) اجرا نشد: خوشهٔ Kubernetes در دسترس نبود، پس خروجیاش «انتظاری» علامت خورده است. قاعدههای IPv6 با nft -c از نظر نحو بررسی شدند ولی اجرا نشدند (شبکهٔ Docker فقط IPv4 بود).
۱. nft ruleset با default-deny برای یک وبسرور. فایل کامل همان است که فصل نقل میکند؛ با nc آزموده شد:
#!/usr/sbin/nft -f
# Default-deny host firewall for a single web server (IPv4 + IPv6 in one table).
flush ruleset
table inet filter {
# Who may reach SSH. Intervals allow CIDR blocks in a set.
set admin_v4 {
type ipv4_addr
flags interval
elements = { 172.16.0.0/12, 10.0.0.0/8 }
}
chain input {
type filter hook input priority filter; policy drop;
# 1. Packets conntrack cannot place in any flow are never legitimate.
ct state invalid counter drop
# 2. Ping flood guard. It must come BEFORE the established rule: after the first
# reply, conntrack marks later echo requests of the same flow ESTABLISHED, and
# they would skip any rate limit placed after that rule.
ip protocol icmp icmp type echo-request limit rate over 5/second burst 10 packets drop
meta l4proto ipv6-icmp icmpv6 type echo-request limit rate over 5/second burst 10 packets drop
# 3. Replies to connections we (or the peer, with a rule below) started.
ct state established,related accept
# 4. Loopback is always local traffic.
iifname "lo" accept
# 5. ICMP: keep the parts that make TCP work (PMTUD, errors, ping; the flood guard is rule 2).
ip protocol icmp icmp type { destination-unreachable, time-exceeded, parameter-problem } accept
ip protocol icmp icmp type echo-request accept
meta l4proto ipv6-icmp icmpv6 type { destination-unreachable, packet-too-big, time-exceeded, parameter-problem, nd-neighbor-solicit, nd-neighbor-advert, nd-router-advert } accept
meta l4proto ipv6-icmp icmpv6 type echo-request accept
# 6. The services this machine offers.
tcp dport { 80, 443 } ct state new accept
ip saddr @admin_v4 tcp dport 22 ct state new accept
# 7. Everything else: log a few samples (nflog group 100), then the policy drops it.
limit rate 5/minute burst 5 packets log group 100 prefix "nft-input-drop: " counter
}
chain forward {
type filter hook forward priority filter; policy drop;
}
chain output {
type filter hook output priority filter; policy accept;
}
}docker network create fwlab
docker run -d --name fwsrv --network fwlab --cap-add NET_ADMIN -v "$PWD/nft:/nft:ro" alpine sh -c \
'apk add -q nftables tcpdump conntrack-tools netcat-openbsd iproute2; sleep 3600'
docker run -d --name fwcli --network fwlab alpine sh -c 'apk add -q netcat-openbsd; sleep 3600'
# listeners on 80, 443, 22 and 5432 inside fwsrv
docker exec fwsrv sh -c 'for p in 80 443 22 5432; do (while true; do echo "port $p" | nc -l -p $p >/dev/null 2>&1; done) & done'
SRV=$(docker inspect -f '{{.NetworkSettings.Networks.fwlab.IPAddress}}' fwsrv) # 172.19.0.2 here
for p in 80 443 22 5432; do docker exec fwcli nc -z -w 2 $SRV $p && echo "$p open" || echo "$p filtered"; done
# before the ruleset: all four open
docker exec fwsrv nft -f /nft/web-server.nft
# after: 80, 443 open; 22 open (the client's 172.19.0.3 is inside admin_v4 172.16.0.0/12); 5432 times outخروجی واقعی پس از بارگذاری: 80 open، 443 open، 22 open، 5432 timeout (خروج nc با کد ۱ پس از انتظار ۲ ثانیه).
| Experiment | Result |
|---|---|
nc -z -w 3 SRV 9999 with an input drop policy | 3.01 s then exit 1 (silent drop) |
Add nft add rule inet filter input tcp dport 9999 reject with tcp reset | 0.00 s, exit 1 ("connection refused" at once) |
nft delete element inet filter admin_v4 '{ 172.16.0.0/12 }' then nc -z -w2 SRV 22 | exit 1: the client is no longer in the set, SSH is filtered |
ping -c 100 -i 0.01 SRV with the flood guard after the established rule | 0% loss: the guard never fired, because later echo requests are ESTABLISHED |
| The same with the guard before the established rule (the file above) | 100 sent, 15 received, 85% loss |
دو ردیف آخر دلیل است که قاعدهٔ ۲ در فایل بالای قاعدهٔ established نشسته.
۲. dropها را لاگ کنید. وقتی کلاینت پورت بسته را کاوش میکند روی گروه nflog شمارهٔ ۱۰۰ گوش دهید:
docker exec -d fwsrv sh -c 'timeout 8 tcpdump -l -n -i nflog:100 > /tmp/nflog.txt 2>&1'
docker exec fwcli nc -z -w 1 172.19.0.2 5432
docker exec fwsrv cat /tmp/nflog.txt
# 17:42:11.697290 IP 172.19.0.3.41840 > 172.19.0.2.5432: Flags [S], seq 2330625817, win 64240, length 0
docker exec fwsrv nft list ruleset | grep 'log group' # counters: "counter packets 2 bytes 120" after two probes
docker exec fwsrv conntrack -L # flows tracked so far۳. پورت published در Docker را با DOCKER-USER محافظت کنید. داخل daemon از نوع Docker-in-Docker (docker run -d --name fwdind --privileged -e DOCKER_TLS_CERTDIR= docker:dind، سپس docker save alpine nginx:alpine | docker exec -i fwdind docker load). دو کلاینت بیرونی کانتینرهای ساده روی پل بیرونیاند؛ آدرس eth0 میزبان Docker برابر 172.17.0.4 بود.
docker exec fwdind docker run -d --name pubtest -p 18080:80 nginx:alpine
# ext1 = 172.17.0.5, ext2 = 172.17.0.6 (two "external" clients)
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable # reachable
docker exec ext2 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable # reachable
# A host-firewall rule on INPUT does not see the published port (ufw installed and enabled, "ufw deny 18080/tcp"):
docker exec fwdind iptables -L ufw-user-input -v -n # DROP tcp dpt:18080 0 packets
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo "still reachable"
# The right place:
docker exec fwdind iptables -I DOCKER-USER -i eth0 ! -s 172.17.0.5 -p tcp -m conntrack --ctorigdstport 18080 -j DROP
docker exec ext1 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ && echo reachable # reachable
docker exec ext2 wget -q -T 3 -O /dev/null http://172.17.0.4:18080/ || echo blocked # wget: download timed out
docker exec fwdind iptables -L DOCKER-USER -v -n
# 3 180 DROP tcp -- eth0 * !172.17.0.5 0.0.0.0/0 ctorigdstport 18080این هم واقعی است: پس از docker run -d -p 127.0.0.1:18081:80 nginx:alpine کلاینت بیرونی در 172.17.0.4:18081 «connection refused/blocked» میگیرد، در حالی که wget http://127.0.0.1:18081/ از خود میزبان کار میکند. قاعدهٔ raw در Docker 28 (-A PREROUTING -d 127.0.0.1/32 ! -i lo -p tcp -m tcp --dport 18081 -j DROP) همین را اعمال میکند. پاکسازی: docker rm -f fwdind ext1 ext2.
۴. نحو iptables و ترجمه. در کانتینری با apk add iptables nftables:
iptables-translate -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT
# nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'
iptables -P INPUT DROP; iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW -j ACCEPT
iptables -S; iptables -L INPUT -v -n --line-numbers; nft list ruleset # same rules, two views۵. NetworkPolicy روی kind (خروجی انتظاری، اینجا اجرا نشد). خوشه را بدون CNI پیشفرض بسازید و Calico را نصب کنید (مستندات kind میگوید disableDefaultCNI: true پشتیبانی میشود و manifestهای Calico شناختهشده کار میکنند)، سپس:
cat <<'YAML' | kind create cluster --config=-
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
networking:
disableDefaultCNI: true
YAML
kubectl apply -f https://raw.githubusercontent.com/projectcalico/calico/v3.28.0/manifests/calico.yaml
kubectl create namespace shop
kubectl -n shop run db --image=nginx:alpine --labels=app=db
kubectl -n shop run api --image=curlimages/curl --labels=app=api --command -- sleep 3600
kubectl -n shop run other --image=curlimages/curl --labels=app=other --command -- sleep 3600
DB=$(kubectl -n shop get pod db -o jsonpath='{.status.podIP}')
kubectl -n shop exec other -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB # expect 200 (default allow)
kubectl apply -f 00-default-deny.yaml
kubectl -n shop exec other -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB # expect 000 and exit 28 (timeout, not refused)
cat <<'YAML' | kubectl apply -f -
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata: {name: db-from-api, namespace: shop}
spec:
podSelector: {matchLabels: {app: db}}
policyTypes: [Ingress]
ingress:
- from: [{podSelector: {matchLabels: {app: api}}}]
ports: [{protocol: TCP, port: 80}]
YAML
kubectl -n shop exec api -- curl -s -m 3 -o /dev/null -w '%{http_code}\n' http://$DB # still 000: default-deny-all also blocks api EGRESSخط آخر مردم را غافلگیر میکند: default-deny-all egress را هم ایزوله میکند، پس Pod مربوط به api برای رسیدن به db هم به قاعدهٔ egress نیاز دارد (سیاست api-egress در manifestها). نیمهٔ egress در default-deny را بردارید (فقط default-deny-ingress را بگذارید) تا 200 مجاز از api و timeout از other را ببینید. نتایج مورد انتظار: timeout (نه refused) برای Podهای ردشده و 200 برای مجازها. روی خوشهای که CNI آن سیاست را اجرا نمیکند هر دستور 200 برمیگرداند.
بدفهمیهای رایج (Common misconceptions)
| Belief | Reality |
|---|---|
| NAT is a firewall | NAT blocks unsolicited inbound by accident (no table row). RFC 4864: "IPv4 NAT was not developed as a security mechanism" |
ufw deny protects Docker published ports | Docker's DNAT sends them through FORWARD; ufw owns INPUT. Use 127.0.0.1: binds or DOCKER-USER |
| A NetworkPolicy always restricts traffic | Only if the CNI enforces it; otherwise "no effect" |
| Security groups and NACLs are the same | SG: stateful, allow-only, per ENI. NACL: stateless, ordered allow and deny, per subnet |
| Stateful firewalls need rules for replies | Replies match the tracked flow; stateless ones (NACL) need an ephemeral-port rule |
| Block all ICMP for safety | Destination unreachable and Packet Too Big make PMTUD work; blocking them causes black holes |
iptables and nftables are separate firewalls | Usually the same kernel engine; iptables-nft writes nftables rules |
DROP is better than REJECT everywhere | DROP hides ports from scanners but slows legitimate failures; use REJECT internally |
| Closing a port in the firewall stops the process listening | The socket still exists; any other path can reach it. Bind to loopback too |
| IPv6 is covered by my IPv4 rules | Separate rules or an inet table are required; with no NAT every host is reachable |
| A rate limit after the established rule limits pings | After the first reply, later echo requests are ESTABLISHED and skip it; place guards earlier |
| Source-IP allow-lists are authentication | Addresses are shared (CGNAT, proxies, VPN) and spoofable behind trustProxies('*'); combine with identity |
| NetworkPolicy has deny rules and ordering | It is allow-only and additive; use CNI extensions for deny |
| Egress does not matter if ingress is locked | Compromise starts outbound: downloads, reverse shells, exfiltration |
چکیده (Cheat sheet)
| Topic | What to remember |
|---|---|
| Rule inputs | 5-tuple, interface, direction, conntrack state; clouds add tags, SG references, labels |
| Stateless vs stateful | Stateful (conntrack, SG, NSG, NetworkPolicy): replies free. Stateless (NACL): allow both directions |
| Default posture | policy drop; established first, then specifics; keep your SSH rule in before enabling |
| Hooks | prerouting, input, forward, output, postrouting; own packets: input/output; routed (containers): forward |
| Tables | raw (notrack), mangle, nat (first packet only), filter (verdicts) |
| Priorities | raw -300, mangle -150, DNAT -100, filter 0, SNAT 100 |
| iptables | iptables -S, -L -n -v --line-numbers, iptables-save, -A/-I/-D, -m conntrack --ctstate |
| nftables | nft list ruleset, nft -f file, nft -c -f file, inet family, sets @name, iptables-translate |
| Verdict semantics (nft) | accept ends one base chain; drop anywhere ends everything |
| Logging | limit rate + log; log group N + tcpdump -i nflog:N; counters for volume |
| ICMP | Allow dest-unreachable, time-exceeded, packet-too-big, NDP; rate-limit echo |
| IPv6 | No NAT, own rules or inet; use meta l4proto, not ip6 nexthdr, for TCP/UDP/ICMPv6 |
| Docker | -p bypasses ufw; use 127.0.0.1: or DOCKER-USER with --ctorigdstport; nftables backend has no DOCKER-USER |
| Kubernetes | Default allow; default-deny + allow-DNS; AND within an item, OR between items; the CNI enforces |
| AWS | SG: ENI, stateful, allow-only, SG references. NACL: subnet, stateless, numbered, ephemeral 1024-65535 |
| GCP / Azure | GCP priority 0-65535 (default 1000), tags; Azure priority 100-4096, defaults at 65000-65500 |
| Egress | Allow-list destinations; NAT gateway + domain filtering; Cilium toFQDNs; egress gateway for stable IPs |
| Listener binding | 127.0.0.1 or a Unix socket for anything that is not public on purpose |
| Audit | nft list ruleset, counters, conntrack -L, ss -ltn, flow logs, nmap from outside |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — پنج فیلد ۵-تایی کداماند و سه چیز دیگر که قاعده میتواند match کند و در آن نیست را نام ببرید. حیاتی
پاسخ
پاسخ: IP مبدأ، IP مقصد، پروتکل، پورت مبدأ، پورت مقصد. همچنین اینترفیسی که بسته از آن آمده یا از آن میرود، وضعیت اتصال (ct state)، پرچمهای TCP، markها، طول بسته، uid مالک روی میزبان، و در ابرها tagها، ارجاع به security group یا labelهای Pod.
۲ — چرا فایروال حالتدار برای پاسخ یک درخواست وب قاعده نمیخواهد و NACL بهجای آن چه میخواهد؟ حیاتی
پاسخ
پاسخ: پاسخ به یک جریان ردیابیشده (conntrack، ردیابی security group) تعلق دارد، پس ضمناً مجاز است. NACL بیحالت است: به قاعدهٔ خروجی نیاز دارد که بازهٔ پورت ephemeral کلاینت را بپوشاند (برای ایمنی ۱۰۲۴ تا ۶۵۵۳۵) و برای جهت معکوس یک قاعدهٔ ورودی.
۳ — iptables -A INPUT -p tcp --dport 22 -m conntrack --ctstate NEW,ESTABLISHED -j ACCEPT را رمزگشایی کنید. حیاتی
پاسخ
پاسخ: به chain مربوط به INPUT (table فیلتر) قاعدهای اضافه کن که بستههای TCP به پورت مقصد ۲۲ را که وضعیت conntrack آنها NEW یا ESTABLISHED است match کند، با هدف ACCEPT. -m conntrack افزونهٔ مطابقت وضعیت را بار میکند. iptables-translate چاپ میکند: nft 'add rule ip filter INPUT tcp dport 22 ct state new,established counter accept'.
۴ — میزبان Docker ufw deny 5432 دارد و کانتینری که با -p 5432:5432 published شده از اینترنت جواب میدهد. چرا، و دو راهحل را نام ببرید. حیاتی
پاسخ
پاسخ: DNAT در Docker در nat PREROUTING مقصد را به کانتینر بازنویسی میکند، پس بسته به FORWARD route میشود و هرگز به INPUT که قاعدههای ufw آنجاست نمیرسد. راهحل: published روی loopback (-p 127.0.0.1:5432:5432) یا یک drop در DOCKER-USER که -m conntrack --ctorigdstport 5432 را match کند (یا اصلاً publish نکنید و از شبکهٔ مشترک استفاده کنید).
۵ — inet در table inet filter یعنی چه و برای IPv6 چرا مهم است؟ مهم
پاسخ
پاسخ: خانوادهٔ inet IPv4 و IPv6 را در یک table میبیند. یک مجموعهقاعده هر دو را پوشش میدهد، پس نمیتوانید IPv4 را قفل کنید و IPv6 را فراموش کنید (در iptables مجموعهقاعدهٔ جدا با ip6tables لازم است).
۶ — NetworkPolicy اعمال کردید و ترافیک تغییری نکرد. دو علت بگویید. مهم
پاسخ
پاسخ: CNI آن را اجرا نمیکند (شیء ذخیره و نادیده گرفته میشود)، یا selectorها با Podها/namespace match نمیشوند (مثلاً namespaceSelector و podSelector بهجای یک آیتم، AND، بهصورت دو آیتم، OR، نوشته شدهاند). همچنین ممکن است سیاست دیگری ترافیک را اجازه دهد (سیاستها جمعشوندهاند).
۷ — چرا بستن همهٔ ICMP مضر است و کدام پیامها باید عبور کنند؟ مهم
پاسخ
پاسخ: Path MTU Discovery به ICMP «fragmentation needed» (نوع ۳ کد ۴ در IPv4) و Packet Too Big در ICMPv6 وابسته است. بدون آنها بستههای بزرگ بیصدا گم میشوند: درخواستهای کوچک کار میکنند و انتقالهای بزرگ گیر میکنند. destination unreachable و time exceeded هم گزارش خطا را پشتیبانی میکنند؛ neighbor discovery در ICMPv6 برای LAN لازم است. echo را میشود محدود کرد.
۸ — درخواستی در flow log برابر ACCEPT است و پاسخش REJECT. علت محتمل و راهحل چیست؟ مهم
پاسخ
پاسخ: NACL بیحالت روی زیرشبکه برای بازهٔ پورت ephemeral قاعدهٔ خروجی (یا برای مسیر معکوس ورودی) ندارد. قاعدهٔ allow برای tcp 1024-65535 را در جهت پاسخ اضافه کنید.
۹ — چرا محدودکنندهٔ نرخ ping باید پیش از ct state established accept باشد؟ تکمیلی
پاسخ
پاسخ: پس از اولین پاسخ conntrack echo requestهای بعدی همان جریان را established علامت میزند؛ محدودی که بعد از قاعدهٔ established بگذارید برای آنها ارزیابی نمیشود. اگر پیش از آن باشد limit rate over 5/second drop روی هر echo request اعمال میشود (آزمایشگاه: ۸۵٪ از دست رفتن زیر سیلاب).
۱۰ — سه دلیل برای کنترل egress و دو راه برای انجامش روی یک Pod در Kubernetes بگویید. مهم
پاسخ
پاسخ: جلوگیری از نشت داده، جلوگیری از reverse shell و دانلود payload پس از نفوذ، محدودکردن مواجههٔ زنجیرهٔ تأمین به registryهای خودتان. در Kubernetes: NetworkPolicy با egress (و قاعدهٔ allow-DNS)، یا Cilium toFQDNs / egress gateway / پراکسی یا فایروال شبکهای که با دامنه فیلتر میکند.
۱۱ — چرا listener ادمین روی Unix socket بهتر از «پورت ادمین محدودشده با قاعدهٔ فایروال» است؟ مهم
پاسخ
پاسخ: پورتی نیست: چیزی برای اسکن نیست، چیزی نیست که تغییر قاعده آن را در معرض بگذارد و دسترسی با مجوز فایل (mode ۰۶۰۰ و دایرکتوری محدود) تعیین میشود. قاعدهٔ فایروال یک چیز دیگر است که میتواند غلط باشد.
۱۲ — وقتی Request::ip() در Laravel آدرس load balancer را برمیگرداند اول چه چیزی را چک میکنید؟ حیاتی
پاسخ
پاسخ: trustProxies در bootstrap/app.php: CIDR مربوط به load balancer (نه *) و headerهای X-Forwarded-* که باید باور شوند را فهرست کنید. بدون آن Laravel از آدرس peer در TCP استفاده میکند.
واژهنامه (Glossary)
| Term | Meaning |
|---|---|
| Firewall | Rules that accept or drop packets or flows by header fields and state |
| Packet filter | A firewall that reads L3-L4 headers only |
| 5-tuple | Source IP, source port, destination IP, destination port, protocol |
| Stateless | Every packet is judged alone; replies need their own rules |
| Stateful | Flows are tracked; replies of an allowed flow pass automatically |
| Default-deny / allow-list | Policy drop, then list what is allowed |
| Policy (chain policy) | Verdict for packets that match no rule in a base chain |
| netfilter | The Linux kernel framework of packet hooks that iptables and nftables use |
| Hook | A point in the packet path: prerouting, input, forward, output, postrouting (and ingress) |
| Table | A container of chains: iptables filter, nat, mangle, raw; nftables tables you name |
| Chain | An ordered list of rules; base chains attach to hooks |
| Base chain | An nftables chain with type, hook, priority |
| Priority | Order among chains at one hook; lower number runs first |
| Verdict | accept, drop, reject, jump, return |
| iptables | The classic command-line tool for netfilter rules |
| iptables-nft | iptables syntax over the nftables backend |
nftables / nft | The modern rule engine and its tool |
Family (ip, ip6, inet, arp, bridge, netdev) | Which protocols a table sees |
| Set / map / concatenation | nftables data structures: list of values, key-to-value lookup, pairs |
| Meter / dynamic set | A set filled from traffic, with per-element rate limits |
| conntrack | The kernel's connection-tracking table |
ct state | Connection state: new, established, related, invalid, untracked |
ESTABLISHED,RELATED | States for replies and flows tied to an existing flow (ICMP errors, FTP data) |
| ctorigdstport | conntrack match on the destination port before DNAT |
| notrack | Raw-table action that skips conntrack |
| DNAT / SNAT / MASQUERADE | Destination, source and dynamic-source address rewriting |
| REJECT vs DROP | Answer with an error vs silently discard |
| LOG / NFLOG | Write a matched packet to the kernel log or to a userspace group |
| ufw | Ubuntu's front-end for netfilter |
| firewalld | Zone-based firewall daemon with nftables backend |
| fail2ban / CrowdSec | Tools that turn log patterns into temporary block rules |
| ICMP / ICMPv6 | Control protocol for errors and diagnostics (and NDP in IPv6) |
| PMTUD | Path MTU Discovery: finding the smallest MTU on a path using ICMP |
| MTU black hole | A path where oversized packets are dropped and no ICMP reaches the sender |
| MSS clamping | Rewriting the TCP MSS so segments fit the path MTU |
| NDP | IPv6 neighbor discovery (ICMPv6 133-137), the ARP replacement |
| DOCKER-USER | iptables chain where user rules run before Docker's own |
| Published port | A container port mapped to a host port with -p |
| Direct routing | Sending packets to a container's address instead of a published port |
| NetworkPolicy | Kubernetes resource defining allowed pod traffic by label, namespace or CIDR |
| CNI | Container Network Interface plugin that implements pod networking and enforces policy |
| Calico, Cilium | CNIs that enforce NetworkPolicy (iptables or eBPF datapath) |
| eBPF | In-kernel programs used by Cilium for policy and load balancing |
ipBlock | NetworkPolicy peer defined by a CIDR |
| Security group | AWS stateful, allow-only firewall attached to a network interface |
| Network ACL (NACL) | AWS stateless, ordered, allow-and-deny firewall attached to a subnet |
| ENI | Elastic Network Interface: the virtual NIC an SG is attached to |
| Ephemeral ports | Short-lived client-side ports (1024-65535 in AWS guidance) used for replies |
| Prefix list | A named set of CIDRs reusable across rules |
| VPC Flow Logs | Per-flow records with ACCEPT or REJECT |
| GCP firewall rule | VPC-level rule with priority, direction, tags or service accounts |
| Azure NSG | Network security group with priorities 100-4096 |
| Service tag / ASG | Azure label for a service's prefixes / for a group of VMs |
| Egress control | Restricting outbound connections |
| NAT gateway | Managed SNAT for private subnets |
| Egress gateway | A fixed exit point for pod traffic |
| FQDN rule | Rule that allows a domain name, resolved to addresses by the enforcer |
| Host firewall | Rules on the machine itself |
| Perimeter | Rules at the edge of a network, subnet or instance |
| WAF | Web application firewall: L7 filtering of HTTP content |
| Defense in depth | Several independent controls so one mistake is not a breach |
| TrustProxies | Laravel middleware that decides which proxies' X-Forwarded-* headers to believe |
| Unix domain socket | A local socket addressed by a file path |
منابع (References)
هر URL با curl fetch شد و متنش زیر scratchpad/sources/firewalls-iptables-nftables-security-groups/ ذخیره شد؛ کد HTTP جز مواردی که ذکر شده ۲۰۰ بود.
Docker, packet filtering and firewalls: https://docs.docker.com/engine/network/packet-filtering-firewalls/
Docker with iptables: https://docs.docker.com/engine/network/firewall-iptables/; Docker with nftables: https://docs.docker.com/engine/network/firewall-nftables/
Docker, port publishing: https://docs.docker.com/engine/network/port-publishing/
nftables wiki: What is nftables? https://wiki.nftables.org/wiki-nftables/index.php/What_is_nftables%3F; Netfilter hooks https://wiki.nftables.org/wiki-nftables/index.php/Netfilter_hooks; Sets https://wiki.nftables.org/wiki-nftables/index.php/Sets; Maps https://wiki.nftables.org/wiki-nftables/index.php/Maps; Meters https://wiki.nftables.org/wiki-nftables/index.php/Meters; Logging https://wiki.nftables.org/wiki-nftables/index.php/Logging_traffic; Quick reference https://wiki.nftables.org/wiki-nftables/index.php/Quick_reference-nftables_in_10_minutes; conntrack matching https://wiki.nftables.org/wiki-nftables/index.php/Matching_connection_tracking_stateful_metainformation
nft man page: https://www.netfilter.org/projects/nftables/manpage.html; iptables-extensions: https://man7.org/linux/man-pages/man8/iptables-extensions.8.html
netfilter packet-filtering HOWTO: https://www.netfilter.org/documentation/HOWTO/packet-filtering-HOWTO-7.html; netfilter hacking HOWTO: https://www.netfilter.org/documentation/HOWTO/netfilter-hacking-HOWTO-3.html
Linux kernel nf_conntrack sysctl: https://www.kernel.org/doc/Documentation/networking/nf_conntrack-sysctl.txt
ufw man page: https://manpages.ubuntu.com/manpages/noble/en/man8/ufw.8.html; firewalld concepts: https://firewalld.org/documentation/concepts.html
Kubernetes, Network Policies: https://kubernetes.io/docs/concepts/services-networking/network-policies/; Declare Network Policy: https://kubernetes.io/docs/tasks/administer-cluster/declare-network-policy/
Cilium, network policy overview: https://docs.cilium.io/en/stable/security/policy/; Cilium introduction (eBPF): https://docs.cilium.io/en/stable/overview/intro/; Calico Kubernetes policy: https://docs.tigera.io/calico/latest/network-policy/get-started/kubernetes-policy/kubernetes-network-policy
kind configuration (disable default CNI): https://kind.sigs.k8s.io/docs/user/configuration/
AWS VPC, security group rules: https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html; network ACLs: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-network-acls.html; custom network ACLs (ephemeral ports): https://docs.aws.amazon.com/vpc/latest/userguide/custom-network-acl.html; infrastructure security (compare SG and NACL): https://docs.aws.amazon.com/vpc/latest/userguide/infrastructure-security.html; VPC Flow Logs: https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html; AWS Network Firewall: https://docs.aws.amazon.com/network-firewall/latest/developerguide/what-is-aws-network-firewall.html
AWS EC2, security group connection tracking: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/security-group-connection-tracking.html
Google Compute Engine API, Firewall resource schema (from the googleapis repository, because cloud.google.com returned 403): https://raw.githubusercontent.com/googleapis/google-api-go-client/main/compute/v1/compute-api.json
Azure, network security groups overview: https://learn.microsoft.com/en-us/azure/virtual-network/network-security-groups-overview
RFC 4890, ICMPv6 filtering recommendations: https://www.rfc-editor.org/rfc/rfc4890; RFC 4864, local network protection for IPv6: https://www.rfc-editor.org/rfc/rfc4864; RFC 1191, path MTU discovery: https://www.rfc-editor.org/rfc/rfc1191; RFC 4821, packetization layer PMTUD: https://www.rfc-editor.org/rfc/rfc4821
Laravel 13, requests (trusted proxies): https://laravel.com/docs/13.x/requests; middleware: https://laravel.com/docs/13.x/middleware