Skip to content

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 -p and 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-listDefault-deny
hookها، tableها، دیاگرام مسیر بستهhookها و tableهای netfilter
ESTABLISHED,RELATED، ct state، ابزار conntrackconntrack و وضعیت‌ها
رمزگشایی -A INPUT -p tcp --dport 22 -m conntrack ...نحو iptables
nft list ruleset، set، map، inet، iptables-nftnftables
ufw و firewalldFront-endها
log، limit rate، meter، fail2banلاگ و محدودکردن نرخ
چرا همهٔ ICMP را نبندیم، PMTUD، hex dumpICMP
NAT نیست که پشتش پنهان شویدفایروال IPv6
-p ufw را دور می‌زند، DOCKER-USER، Docker 28 به بعدDocker و فایروال
پیش‌فرض allow، selectorها، پشتیبانی CNI، eBPFKubernetes 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، webhookLaravel
کدام کنترل برای کدام وضعیتانتخاب
از مونولیت تا توزیع‌شدهدر معماری
بازتولید روی ماشین خودتانآزمایشگاه
بدفهمی‌ها، چکیده، واژه‌نامهبدفهمی‌ها، چکیده، واژه‌نامه

همه‌چیز در یک دقیقه (Everything in one minute) ​

قاعده به چه چیزی نگاه می‌کند. هر ردیف بعداً باز می‌شود.

Match fieldExampleNeeds state?Where it exists
Source / destination IPip saddr 10.0.0.0/8Noiptables, nft, SG, NACL, NetworkPolicy ipBlock
Protocoltcp, udp, icmp, ipv6-icmpNoeverywhere
Source / destination porttcp dport 22Noeverywhere (not ICMP)
TCP flagstcp flags synNoiptables, nft (not clouds)
Interface and directioniifname "eth0", -i eth0, INPUT vs OUTPUTNohosts; clouds attach rules to an ENI, a subnet or a NIC
Connection statect state established,relatedYesiptables -m conntrack, nft ct state, SG (implicit)
Labels instead of addressespod labels, SG references, tags, service tagsDependsNetworkPolicy, SG, GCP tags, Azure ASG

پنج جایی که فهرست قاعده‌ها می‌تواند باشد.

PlaceProductScopeDefault for new traffic
The Linux hostiptables, nftables, ufw, firewalldOne machine, all interfacesACCEPT (until you set a policy)
The container bridgeDocker's own rules in DOCKER-* chainsContainers on this hostPublished ports open to everyone
The cloud network interfaceAWS security group, GCP firewall rule, Azure NSGOne instance (or a tagged set)Inbound deny, outbound allow
The cloud subnetAWS network ACLEverything in a subnetDefault NACL allows all; a new custom one denies all
The podKubernetes NetworkPolicy (enforced by the CNI)Pods in a clusterAllow all until a policy selects the pod

پنج شکستی که باید انتظارش را داشت.

SymptomUsual causeChapter section
SG allows 443, clients still time outNACL blocks the return traffic to ephemeral portsFailures
ufw denies 5432, the database is public anywayDocker published the port; the packet never reaches INPUTDocker
NetworkPolicy applied, nothing changedThe CNI does not enforce NetworkPolicyKubernetes
Load balancer marks all targets unhealthyHealth-check source not allowed by SG or NACLFailures
Small requests work, big uploads hangICMP "fragmentation needed" / "packet too big" is droppedICMP

چرا فایروال وجود دارد (Why firewalls exist) ​

ماشینی که روی یک پورت گوش می‌دهد هر کسی را که به آن برسد می‌پذیرد. بیشتر سرویس‌ها هرگز برای روبه‌رو شدن با کل اینترنت طراحی نشده‌اند: یک پایگاه‌داده، یک Redis، یک پنل ادمین، sshd با ورود با رمز، یک endpoint متریک. فایروال ارزان‌ترین جا برای گفتن «این پورت فقط برای این کلاینت‌هاست» است، چون برای همهٔ برنامه‌های روی ماشین کار می‌کند، از جمله آن‌هایی که کسی نصبشان را یادش نیست.

Without a firewallWith one
Every listening socket is a public serviceOnly the ports you named are reachable
One misconfigured service (Redis without a password) is a breachThe same mistake is reachable only from the allowed range
A compromised process can talk to anythingEgress rules limit where it can send data or fetch tools
Scanning finds everything in minutesDropped packets give scanners nothing; logs show who tried

تصویری از زندگی روزمره. ساختمانی با دربان. دربان نامه‌های شما را نمی‌خواند (آن کار برنامه است)؛ می‌بیند شما کی هستید (آدرس مبدأ)، از کدام در می‌آیید (پورت) و آیا کسی از داخل برایتان زنگ زده (وضعیت اتصال). دربان بی‌حالت یک فهرست برای ورود و یک فهرست برای خروج دارد و هر بار هر دو را چک می‌کند. دربان حالت‌دار یادش می‌ماند «این مهمان دعوت شده بود» و پاسخ را بی‌نگاه دوباره رد می‌کند.

سه بدفهمی، از همین ابتدا.

MisunderstandingReality
"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) ​

SourceWhat 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 4821Path MTU Discovery for IPv4 and the "packetization layer" variant that survives dropped ICMP
AWS VPC security groupsThe 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 eBPFPolicy 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......
OffsetBytesFieldValueA rule that matches it
0x003e20 ea32 077e / 4660 4252 9bd4dest MAC / source MACthe two NICsether saddr (rarely used)
0x0c0800EtherTypeIPv4meta protocol ip
0x0e45version 4, header length 5 words20-byte header(implicit)
0x1640 / 06TTL 64 / protocol 6TCPip protocol tcp (-p tcp)
0x1aac13 0003source IP172.19.0.3ip saddr 172.19.0.3
0x1eac13 0002destination IP172.19.0.2ip daddr 172.19.0.2
0x22cca2source port52386 (ephemeral)tcp sport 52386
0x241538destination port5432tcp dport 5432
0x2f02 (in a002: header length 10 words, flags 02)TCP flagsSYN onlytcp flags syn, ct state new

سناریوهای واقعی: یک قاعدهٔ allow برای 10.0.0.0/8 روی پورت ۲۲؛ drop همهٔ SYNهای پورت ۵۴۳۲ از بیرون VPC؛ یک قاعدهٔ egress که فقط tcp dport 443 را به یک ارائه‌دهندهٔ پرداخت اجازه می‌دهد؛ یک security group که به‌جای آدرس، نام security group دیگری را می‌آورد.

ProductFields it can match
iptables / nftablesEverything in the table above, plus marks, packet length, owner uid (-m owner), rate, hash, geo (extension)
AWS security groupProtocol, port range, ICMP type and code, source or destination as CIDR, prefix list or another SG
AWS network ACLProtocol, port range, ICMP type and code, CIDR; numbered rules
GCP VPC firewall ruleProtocol and ports, source or destination ranges, source and target tags or service accounts, direction, priority
Azure NSGThe 5-tuple, service tags, application security groups, priority
Kubernetes NetworkPolicyPod 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 در حال تایپ شما را نمی‌کُشد (حالت‌دار، چون اتصال از قبل ردیابی شده).

ProductStateful?Detail
Linux netfilterOnly if you use conntrack (ct state)Loaded by default when a rule needs it; you write ct state established,related accept yourself
AWS security groupYes"responses to inbound traffic are allowed to flow out of the instance regardless of outbound security group rules, and vice versa"
AWS network ACLNo"responses to that traffic are not automatically allowed"
GCP VPC firewallYes (as designed)See the cloud section for the sourcing note
Azure NSGYes"Network security group rules only affect new connections"
Kubernetes NetworkPolicyYes"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 اضافه نکرد.

ProductDefault 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)
firewalldInter-zone traffic denied, intra-zone allowed by zone principles
AWS security groupNo inbound rules (deny), one allow-all outbound rule
AWS default NACLAllows all inbound and outbound; a new custom NACL denies all until you add rules
Azure NSGDefault 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ها اجرا می‌شود.

NIC inpacket arrivesPREROUTINGraw, mangle, nat(DNAT)routingdecisionINPUTmangle, filterLocal processnginx, php-fpm, sshdFORWARDmangle, filterOUTPUTraw, mangle, nat, filterPOSTROUTINGmangle, nat(SNAT)NIC outpacket leavesfor this hostother destLocal replies and locally started connections take the dashed path: process, OUTPUT, routing, POSTROUTING.A routed packet (host as router) never touches INPUT or OUTPUT: PREROUTING, FORWARD, POSTROUTING.

iptables قاعده‌ها را در tableها می‌چیند؛ هر table هدفی دارد و در چند hook chain ثبت می‌کند:

TablePurposeHooks (chains) it hasTypical rule
rawRun before conntrack; mark packets as NOTRACKPREROUTING, OUTPUTExempt a busy DNS server from conntrack; Docker drops direct-routed packets here
mangleChange packet fields (TOS, TTL, marks)all fivePolicy routing marks, MSS clamping
natRewrite addresses; consulted for the first packet of a flow onlyPREROUTING (DNAT), OUTPUT, POSTROUTING (SNAT, MASQUERADE), INPUT-j DNAT, -j MASQUERADE (see NAT)
filterAccept or dropINPUT, FORWARD, OUTPUTYour allow-list
securitySELinux-style labelsINPUT, FORWARD, OUTPUTRare

ترتیب درون یک 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 بعد.

TimelineWhat the kernel does with a packet to a published container port
1NIC receives the frame, conntrack creates an entry (priority -200)
2nat PREROUTING DNAT rewrites host:8080 to 172.18.0.2:80 (priority -100)
3Routing decision: the destination is a local bridge, not this host, so the packet goes to forward
4filter FORWARD: DOCKER-USER, then Docker's own chains
5nat POSTROUTING may masquerade; the frame leaves through the bridge

سناریوهای واقعی: قاعدهٔ iptables روی INPUT که برای پورت کانتینر هیچ کاری نمی‌کند؛ قاعدهٔ OUTPUT که worker پی‌اچ‌پی‌-FPM را از رسیدن به میزبان پرداخت می‌بندد؛ قاعدهٔ raw که یک سرویس UDP پرسروصدا را از جدول conntrack بیرون نگه می‌دارد.

ProductWhere its rules attach
iptablesFixed chains in fixed tables (INPUT, FORWARD, ...)
nftablesBase chains you create with type filter hook input priority filter; in any table; regular chains you jump to
ufwufw-before-input, ufw-user-input and similar chains jumped to from INPUT/FORWARD/OUTPUT
firewalldZones compiled to nftables (or iptables) chains with names like filter_IN_public
DockerDOCKER-USER, DOCKER-FORWARD, DOCKER, DOCKER-CT, DOCKER-BRIDGE, DOCKER-INTERNAL in filter; DOCKER in nat; PREROUTING drops in raw
Kubernetes kube-proxyKUBE-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 می‌نامد:

StateMeaningTypical rule
newFirst packet of a flow, not seen beforetcp dport 443 ct state new accept
establishedPart of a flow with traffic in both directionsct state established,related accept (first rule)
relatedA new flow that is tied to an existing one: an ICMP error about a flow, an FTP data connection through a helperSame rule as above
invalidCannot be placed in any flow (out-of-window TCP, bogus flags)ct state invalid drop
untrackedExempted 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 کند.

KnobMeaningDefault / note
net.netfilter.nf_conntrack_maxMax entries in the tableDefault 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_establishedIdle seconds before an established TCP entry expires432000 (5 days) in the kernel doc
conntrack -C / conntrack -SCount of entries / per-CPU statistics (insert_failed, drop)First thing to check on a busy node
conntrack -ELive event streamWatch 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)
PieceMeaning
-A, -I [n], -D, -R, -F, -X, -NAppend, insert (default position 1), delete, replace, flush chain, delete chain, new chain
-P INPUT DROPSet the chain policy
-s, -d, -i, -oSource, destination, in-interface, out-interface; ! negates
-p tcp --dport 22, --sport, --dports 80,443Protocol and ports; --dports needs -m multiport
-m state --state / -m conntrack --ctstateConnection state (the second is current; state is the old spelling)
-m limit --limit 5/min --limit-burst 5Token-bucket match, usually in front of LOG
-m recent, -m hashlimit, -m connlimitPer-source counters, per-source rate, per-source connection count
-j ACCEPT, DROP, REJECT, LOG, RETURN, DNAT, MASQUERADE, or a chain nameTarget; 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 برای سرویس داخلی که باید سریع شکست بخورد.

ProductNotes
iptables-legacy (xtables)The original kernel interface; separate binaries per family (iptables, ip6tables, arptables, ebtables)
iptables-nftThe same command line, but rules are stored as nftables rules; iptables --version prints (nf_tables)
iptables-restoreAtomic 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 ideaSyntaxWhy it beats iptables
One table for both familiestable inet filterOne rule covers IPv4 and IPv6; no ip6tables twin
Anonymous settcp dport { 80, 443 }One rule instead of two, evaluated as a set
Named setset admin_v4 { type ipv4_addr; flags interval; } then ip saddr @admin_v4Update the set at runtime with nft add element; no rule reload
Interval setsflags interval, elements = { 10.0.0.0/8 }CIDR blocks as set members
Dynamic sets and metersflags dynamic, timeout; update @s { ip saddr limit rate 3/minute }Per-source rate limits (iptables hashlimit, recent)
Mapsdnat 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
Concatenationsip saddr . tcp dport @allowedA set of pairs: "address X may reach port Y" in one lookup
Atomic reloadnft -f fileThe 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 را جایگزین می‌کند.

Productnftables status
Current Debian, Ubuntu, RHEL and Fedora releasesiptables is the nft shim by default (check iptables --version)
firewalldnftables backend in current releases
Dockeriptables backend by default; the Docker page documents an nftables backend, marked experimental there, in which "there is no DOCKER-USER chain"
Kubernetes kube-proxyiptables and ipvs modes; an nftables mode also exists
CiliumeBPF 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
Questionufwfirewalld
Default distributionsUbuntu, Debian-familyRHEL, Fedora, CentOS Stream, SUSE
ModelAllow/deny/reject/limit rules with a default policyZones, services, rich rules, policies between zones
Backendiptables or nftables (via the iptables-nft shim)nftables by default
Change without restartufw allow ...firewall-cmd --add-service (runtime) plus --permanent and --reload
Docker interactionDocker's published ports bypass itDocker 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 پنج محدود است و آزمایش قبلی سطل را مصرف کرده بود. این همان محدودکننده است که کارش را می‌کند.

ToolDoes what
log / LOGWrites to the kernel ring buffer (dmesg, journalctl -k); prefix tells you which rule
log group N / NFLOGSends the packet to a userspace listener (tcpdump -i nflog:N, ulogd)
counterPackets and bytes per rule; no log volume
limit rateToken bucket per rule
Meters (dynamic sets)Per-source buckets with a timeout
fail2banReads auth logs and inserts per-IP drop rules into a set or chain for a time
CrowdSecShared 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 messageIPv4 type/codeICMPv6 typeAllow in?Why
Destination unreachable (incl. fragmentation needed)3 / 0-15, 3/41YesErrors for flows you started; PMTUD
Packet Too Big(3/4 on IPv4)2YesPMTUD on IPv6; routers do not fragment
Time exceeded113Yestraceroute, loops
Parameter problem124YesHeader errors
Echo request / reply8 / 0128 / 129Optional, rate-limitedReachability checks; RFC 4890 says IPv6 echo need not be filtered
Neighbor / router discoveryn/a (ARP)133-136Yes on IPv6NDP replaces ARP; blocking it breaks the LAN
Redirect5137NoCan 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).

ProductHow to allow the essential ICMP
nftablesip 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 groupAdd 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 ACLThe 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 می‌کند.

ProductIPv6 detail
AWS security groupSeparate 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
GCPSource and destination ranges accept IPv4 and IPv6 CIDRs; the API says "Both IPv4 and IPv6 are supported"
Linuxip6tables, or inet family in nftables; ufw manages both when IPV6=yes
Dockerip6tables 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 شود.

Internetto host:8080nat PREROUTINGDOCKER: DNAT to172.18.0.2:80routing:dest is acontainerINPUT (ufw)never reachedFORWARDDOCKER-USER firstDOCKER-FORWARDDOCKER, DOCKER-CTContainernginx :80only if dest = hostPut your own rules in DOCKER-USER (iptables) or a separate nft tablewith a forward-hook base chain (nftables). Match the ORIGINAL port with-m conntrack --ctorigdstport, because DNAT has already rewritten it.

قاعده‌های واقعی روی 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 است (پایین‌تر را ببینید).

TimelineExperiment (all real, run from two other containers as "external" clients)
1ext1 and ext2 reach the published port: wget http://172.17.0.4:18080/ succeeds for both
2Real 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
3iptables -I DOCKER-USER -i eth0 ! -s 172.17.0.5 -p tcp -m conntrack --ctorigdstport 18080 -j DROP goes in
4ext1 (172.17.0.5) still succeeds; ext2 times out ("download timed out"); the rule's counter shows 3 packets dropped

چطور پورت‌های published را درست محدود کنیم:

GoalHowWhy 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 itA 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 DROPDOCKER-USER runs before Docker's rules; DNAT has already rewritten the destination, so you match the original with conntrack
Allow repliesiptables -I DOCKER-USER -m state --state RELATED,ESTABLISHED -j ACCEPT placed before the dropsContainers' outgoing flows must come back
Everything private by defaultChange the default publish address: daemon ip: 127.0.0.1, or network option com.docker.network.bridge.host_binding_ipv4=127.0.0.1New -p flags bind to loopback unless you name an address
Not published at allSame user-defined network, no -p; talk by container nameContainers reach each other on the bridge; nothing is reachable from outside
nftables backendCreate 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 روی میزبان تنها راه ورود است.

ProductWhat 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
ufwDoes not control published ports; use ufw-docker-style rules in DOCKER-USER, or bind to loopback
firewalldDocker adds a docker zone, target ACCEPT; restrict with a rich rule or a policy
PodmanUses netavark with its own nftables/iptables chains; rootless Podman publishes through a userspace proxy
ComposeSame 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 نمی‌تواند دسترسی به خودش را ببندد.

ns: ingress-nginxpodapp.kubernetes.io/name=ingress-nginxns: shop (default-deny ingress + egress)apilabel app=apilistens :8080dblabel app=dblistens :5432otherlabel app=othernot selected: deniedpayments203.0.113.0/24ns: kube-systemkube-dns pods, UDP/TCP 53TCP 8080TCP 5432TCP 443 (ipBlock)DNS egress (allow-dns policy)db has no egress rule forapi, only replies are allowed"other" to db: dropped

قاعده‌های 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=alice

namespace فیلد نامی برای match ندارد، اما "The Kubernetes control plane sets an immutable label kubernetes.io/metadata.name on all namespaces"، پس روی همان label match کنید.

گام ۱، default-deny برای هر دو جهت در یک namespace (الگوی مستندات Kubernetes):

yaml
# 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"، پس آن را اجازه دهید:

yaml
# 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 بیرونی برسد:

yaml
# 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 }
yaml
# 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 }
FieldMeaningTrap
podSelector: {}All pods in the policy's namespaceEmpty selector means everything, not nothing
policyTypesIngress, Egress or bothIf omitted, Ingress is always set; Egress only if the policy has egress rules
ingress[].from / egress[].toList of peers: podSelector, namespaceSelector, ipBlockAND within an item, OR between items
ipBlockA CIDR with optional exceptMeant 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, endPortA port or a rangeThe CNI must support endPort, otherwise only the single port is applied
protocolTCP, UDP, SCTPFor ICMP and ARP the behaviour is undefined
ingress: [{}]Allow all ingressUsed 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.

CNIEnforces core NetworkPolicy?Extra policy API
CalicoYesGlobalNetworkPolicy, deny rules, ordering, host endpoints
CiliumYes (eBPF)CiliumNetworkPolicy, FQDN egress, L7 HTTP/Kafka rules, Hubble flow logs
Antrea, Kube-routerYesOwn CRDs (Antrea)
kind default (kindnetd)Check before relying on it; install Calico with disableDefaultCNI: trueNone
A CNI with no policy controllerNo: the object is stored and ignoredNone
Managed clusters (EKS, GKE, AKS)Needs the provider's policy engine switched on or a plugin installedProvider-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."

Client198.51.100.9:51344VPC subnet 10.0.1.0/24 (network ACL boundary)Network ACLstateless, orderedIN 100 allow tcp 443IN * deny allOUT 100 allow tcp 1024-65535OUT * deny allSecurity groupstateful, allow onlyIN allow tcp 443from 0.0.0.0/0reply allowed byconnection tracking(no OUT rule needed)InstanceENI, nginx :443Solid: request to :443. Dashed: reply from :443 to the client's ephemeral port 51344.Forget the NACL outbound rule for 1024-65535 and the reply dies at the subnet edge.
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ها) باشد.

PropertyAWS security groupAWS network ACLGCP VPC firewall ruleAzure NSGKubernetes NetworkPolicy
Attached toENI (instance, LB, Lambda)SubnetVPC network, selecting by tag or service accountSubnet or NICPods (by label)
StatefulYesNoYes (see note)YesYes
Allow / denyAllow onlyAllow and denyAllow and denyAllow and denyAllow only
Rule orderNone (all rules unioned)Ascending rule number, first matchPriority 0-65535, lower first; deny wins tiesPriority 100-4096, lowest firstNone (additive)
Default inboundDenyDefault NACL allow all; custom NACL deny allImplied deny (priority 65535)Deny (65500)Allow until selected
Default outboundAllow allSame as inboundImplied allow (priority 65535)Allow (65000-65500 defaults)Allow until selected
References to other groupsSG IDs, prefix listsCIDRs onlyTags, service accountsService tags, ASGsPod and namespace selectors
Changes affect existing flowsNot tracked onesYes immediatelyPer cloud docsNoCNI-defined
LoggingVPC Flow LogsVPC Flow LogsFirewall Rules LoggingVirtual network flow logs (NSG flow logs retire 2027-09-30)CNI-specific (Hubble, Calico flow logs)
CostFreeFreeFreeFreeFree (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های خودتان آنچه یک بستهٔ مخرب می‌تواند به آن برسد را کم می‌کند.

LayerHow to restrict egressLimit
Hostnftables output chain with policy drop and per-destination accepts (the Go generator below emits it)IP-based; CDN addresses change
DockerDOCKER-USER rules on -o ext_if, an internal network (docker network create --internal), a forward proxy containerPer host
Security groupRemove the default allow-all outbound rule, add specific onesSG cannot filter by domain; cannot block DNS to the Route 53 Resolver
NACLSubnet-wide outbound deny and allow listStateless: replies need return rules
KubernetesNetworkPolicy egress with ipBlock/selectors; Cilium toFQDNs (see the manifest below); egress gateways give pods a fixed source IPCore NetworkPolicy has no DNS names
Cloud DNS-awareAWS Network Firewall (domain allow-lists via stateful rule groups), Route 53 Resolver DNS Firewall, Azure Firewall FQDN rules, GCP Cloud NAT plus firewall policiesPaid service; inspection point
ProxyOutbound HTTP(S) only through a proxy that enforces an allow-list (squid, Envoy)Apps must honour HTTP_PROXY
yaml
# 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) یعنی دو دیوار مستقل، تا یک قاعدهٔ غلط نفوذ نباشد.

AspectPerimeter (SG, NACL, edge firewall)Host firewall (nftables, ufw)
Managed byCloud API, Terraform, network teamConfig management, image bake, the server owner
SeesTraffic entering or leaving the instance or subnetEverything incl. east-west and loopback
Survives a root compromise on the hostYesNo: root can flush it
Central auditYes (flow logs)Per host (counters, logs)
Per-process controlNoYes: -m owner --uid-owner on OUTPUT
Typical failureToo-broad CIDR such as 0.0.0.0/0Rules 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
ServiceWhere to set the bind address
PostgreSQLlisten_addresses = 'localhost' (default) or a private IP
MySQL / MariaDBbind-address = 127.0.0.1
Redisbind 127.0.0.1 -::1, protected-mode yes
MongoDBnet.bindIp: 127.0.0.1
nginx / php-fpmlisten 127.0.0.1:9000; or a Unix socket listen = /run/php/php-fpm.sock
Docker-p 127.0.0.1:8080:80
Laravelphp artisan serve --host=127.0.0.1; Octane --host=127.0.0.1 behind nginx
Gohttp.Server{Addr: "127.0.0.1:8080"} instead of ":8080"
KubernetesContainers 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 نمی‌بیند. هرکدام چیزهایی را می‌بندد که دیگری نمی‌تواند.

ControlLayerSeesBlocksDoes not stop
nftables / iptablesL3-L4 (conntrack adds state)5-tuple, flags, stateUnwanted ports and sourcesSQL injection on an allowed port
AWS security groupL3-L4, stateful, per ENI5-tuple of new flowsSame, at the instanceAnything on an allowed port
AWS network ACLL3-L4, stateless, per subnet5-tuple per packetSubnet-wide CIDRs and portsApplication attacks
NetworkPolicyL3-L4, per podPod labels, CIDRs, portsEast-west trafficApplication attacks, anything L7
Network firewall (AWS Network Firewall, NGFW)L3-L7 inspectionDomain names (SNI), signaturesExfiltration to unlisted domainsEncrypted payload content
L7 proxy / ingress / API gatewayL7HTTP method, path, headersUnauthenticated routes, oversized bodiesNetwork-layer floods
WAFL7Request contentSQLi, XSS patterns, bad bots, rate abuseDirect access to a non-HTTP port
mTLS / service meshL4-L7 identityCertificate identityCallers without a valid identityCompromised but valid services

کاهش DDoS، طراحی قاعدهٔ WAF و کنترل bot در DDoS و امنیت شبکه است؛ mTLS در mTLS.

شکست‌های رایج (Common failures) ​

SymptomCauseHow to confirmFix
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 replyVPC Flow Logs show ACCEPT inbound and REJECT for the return flow; compare NACL outbound rulesAdd outbound allow tcp 1024-65535 (and inbound for the reverse case)
Database port is public although ufw status says denyDocker published it; DNAT sends it through FORWARD, not INPUTdocker ps shows 0.0.0.0:5432->5432; iptables -t nat -S DOCKERBind 127.0.0.1:5432:5432, or a DOCKER-USER drop matching --ctorigdstport 5432
NetworkPolicy applied, traffic unchangedCNI does not implement it, or the policy selects different labelskubectl describe networkpolicy; check the CNI; labels on the podsUse Calico/Cilium/Antrea/Kube-router; fix selectors
After default-deny egress, every pod fails with name errorsDNS not allowednslookup times outAdd the allow-DNS policy
Load balancer marks every target unhealthyThe target's SG or NACL blocks the health-check source (the LB's SG or subnet)Target group health reason; SG inbound rulesAllow 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 hangICMP "fragmentation needed" or "packet too big" dropped: MTU black holeping -M do -s 1472 host fails at a size, tracepath, tcpdump icmpAllow ICMP type 3 code 4 and ICMPv6 type 2; clamp MSS
SSH worked, then died right after ufw enable or policy dropEstablished rule missing or placed after the dropConsole access; nft list ruleset orderct state established,related accept first; schedule an auto-revert
New connections fail under load, old ones workconntrack table fulldmesg shows a conntrack "table full" message; conntrack -CRaise nf_conntrack_max, shorten timeouts, notrack for known flows
IPv4 locked down, IPv6 openNo ip6tables/inet rules, or SG missing ::/0ss -ltn6, nmap -6Use an inet table, add IPv6 rules
Rules vanish after rebootNot persistednft list ruleset is empty after bootnftables.service with /etc/nftables.conf; netfilter-persistent
iptables -L looks empty but traffic is still filteredRules live in nftables tables, another table, or another network namespacenft list ruleset, iptables-nft -S, ip netnsList with the matching tool and namespace
Admin UI reachable from the internetService bound to 0.0.0.0 and SG too widess -ltn, scan from outsideBind to loopback or a Unix socket; narrow the SG
Webhook provider cannot reach youSource IP not allowed by SG, or provider ranges changedFlow logs; provider's published rangesAllow the provider ranges from a managed list; verify signatures too

ممیزی (Auditing) ​

QuestionCommandWhat to read
What rules exist, in nft form?nft list rulesetTables, chains, hooks, priorities, policies; -a adds handles
What rules exist, in iptables form?iptables -S, iptables-saveReplayable 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 counterPacket and byte counters per rule
Live trace of one packetnft monitor trace after meta nftrace set 1 on a matchEach rule the packet passes
What flows are tracked?conntrack -L, conntrack -C, conntrack -SState, NAT tuples, timeouts, insert_failed
What is listening?ss -ltnupLocal address (loopback or all interfaces) and the process
What is reachable from outside?nmap -sS -p- host from another network, nc -zv host portOpen vs filtered (timeout) vs closed (refused)
Which firewall is active?ufw status verbose, firewall-cmd --list-all, systemctl status nftablesThe front-end's view
What did the cloud allow or reject?AWS VPC Flow Logs, GCP Firewall Rules Logging, Azure virtual network flow logsACCEPT/REJECT per 5-tuple
What does Kubernetes enforce?kubectl get networkpolicy -A, kubectl describe networkpolicy, cilium monitor --type drop, calicoctl get networkpolicyPolicies, selectors, drops
Docker's rulesiptables -S DOCKER-USER, iptables -t nat -S DOCKER, docker network inspectPublished 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 / statementEffectNote
acceptStops this base chain; next base chain at the same hook still runsIn iptables, ACCEPT in a built-in chain ends that chain's traversal for that table
dropPacket discarded, sender sees nothingFinal for the whole ruleset
rejectDiscards and sends ICMP unreachable or TCP RSTFaster failure; leaks that a host exists
jump chain / goto chainEvaluate a regular chain; jump returns, goto does notChains in other tables cannot be called
returnBack to the calling chainPolicy applies at the end of a base chain
log / counter / limitNon-terminating statementsPlace before the verdict
dnat / snat / masqueradeNAT in the nat hooks, first packet of a flow onlyReply and later packets are translated by conntrack
notrackSkip 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).

رفتار هر محصول که غافلگیر می‌کند.

ProductBehaviour
Linux, iptables REJECT vs DROPDROP hides a closed port (client times out, scanner learns nothing); REJECT is friendlier for internal clients and avoids long timeouts
Linux, loopbackAllow iifname "lo" or local services stop talking to each other (DNS stub, PHP-FPM over TCP)
Linux, rp_filterReverse path filtering can drop asymmetric traffic regardless of your rules
DockerContainer-to-container on one user-defined bridge is allowed; published ports are DOCKER-chain rules; iptables: false breaks masquerading
AWSSG changes apply instantly to new flows; tracked flows survive; NACL changes break flows immediately
GCPPriority 0-65535; deny wins ties; implied rules at 65535
AzurePriority 100-4096; same-priority conflicts are not allowed; existing connections survive a rule removal
KubernetesAdditive allow-only model; enforcement by CNI; NodePort or LB source IP may be rewritten before policy

حل مسئله‌های کلاسیک (Solving the classic problems) ​

ProblemSolutionHowCost / limitation
A server must expose only web and SSHDefault-deny host policy + security grouppolicy drop, established first, then tcp dport {80,443} and an admin setRemote lockout risk while editing
Rules drift between hostsRules generated from one policy fileThe Go generator below, Terraform, AnsibleA generator is code you must test
A container's published port is publicBind to loopback, or DOCKER-USER filter-p 127.0.0.1:..., --ctorigdstport rulesPer host; nftables backend needs its own table
Namespace has no isolationDefault-deny + allow-DNS + explicit allowsNetworkPolicy templates per namespaceNeeds an enforcing CNI
Return traffic blocked in a subnetEphemeral return rule on the NACL, or no custom NACLOutbound allow tcp 1024-65535Wide port range, a coarse control
Brute force on SSHPer-source rate limit, key-only auth, VPN or bastionnft meter, fail2ban, VPNShared NAT addresses get caught together
Admin UI must not face the internetUnix socket or loopback listener + CIDR middlewareGo example below, Laravel middlewareAdmin tools must run on or tunnel to the host
Exfiltration after a compromiseEgress allow-listoutput chain policy drop, NetworkPolicy egress, FQDN firewallMaintenance of allowed destinations
Webhook from a providerSource CIDR allow-list plus signatureallow.cidr middleware, HMAC checkProvider ranges change
Big uploads hangAllow ICMP errors, clamp MSSRules aboveNone 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 را بگیرید.

فایل سیاست:

yaml
# 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]

برنامه:

go
// 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، پورت را حذف کنید.

go
// 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
DetailWhy it matters
syscall.Umask(0o177) around ListenThe socket is created 0600 from the start; chmod after Listen leaves a window
Removing a stale socket firstA crashed run leaves the file; Listen would fail with "address already in use"
Directory mode 0750The directory is a second permission check
Public server on 127.0.0.1:8080A reverse proxy on the host is the only public listener
Reaching it remotelyssh -L can forward a local port to a remote Unix socket (-L 9090:/run/app/admin.sock); see VPNs and tunnels
ContainersMount 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:

sql
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
<?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
<?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
<?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
<?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
<?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
<?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();
    }
}
PieceWhy
$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 canNetwork, identity, permission: three independent checks
abort(404) and a warning logHides the route and leaves an audit trail with REMOTE_ADDR
Webhook IP allow-list plus hash_equals on an HMACIP ranges are shared and change; the signature proves possession of the secret
Config from .envADMIN_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) ​

SituationRecommendationExtra techniqueReason
One VPS running nginx, PHP, Postgresnftables (or ufw) default-deny: 80, 443, SSH from your IPBind Postgres and PHP-FPM to loopback or a socket; fail2banTwo walls: firewall and listener
Cloud web appSecurity groups per tier referencing each other; default NACLFlow logs; no 0.0.0.0/0 except the LB's 443Least privilege without address bookkeeping
Need to block a hostile CIDR subnet-wideCustom NACL deny rule with a low numberReturn-port rules; WAF for L7SGs cannot deny
Docker host with Compose127.0.0.1: publishes + a reverse proxyDOCKER-USER rules, cloud SGufw does not see published ports
Kubernetes multi-tenantDefault-deny + allow-DNS per namespaceCalico/Cilium for logging, FQDN, global policyCore NetworkPolicy is allow-only and namespaced
Locking down egress for a payments serviceEgress allow-list by CIDR; FQDN with Cilium or a firewall serviceNAT gateway with a fixed IP, domain filteringLimits exfiltration and supply-chain callbacks
Public admin toolDo not expose it: VPN, bastion, SSH tunnel, Unix socketCIDR middleware as a backstopA closed port cannot be attacked
Webhook receiverPublic endpoint, signature verificationProvider CIDR allow-list from a managed listIPs are not identity
Home router with IPv6Stateful inbound-deny firewallAllow specific services onlyNo NAT, so no accidental protection
Very large blocklists or many rulesnftables sets or ipset, or eBPFReload atomically from filesLinear iptables chains do not scale
Compliance and auditFlow logs plus change-managed rules in GitTerraform plan reviewProves 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 / sizeWhat breaks firstWhat to change
1 server, 1xDocker publishes a database, or 0.0.0.0 listenersLoopback binds, default-deny, one reviewed ruleset
10 servers, 10xRule drift; hand-edited security groupsGenerate rules from one policy file or Terraform module; prefix lists; flow logs on
100 services, 100xAddress-based rules do not map to pods that moveNetworkPolicy by label, CNI with identity (Cilium), SG references, default-deny templates
Thousands of rules or nodesLinear iptables chains slow connection setup; conntrack tables fillnftables sets, eBPF datapath, kube-proxy in IPVS or nftables mode, notrack where safe
Multi-region, many accountsInconsistent baselines, shadow rulesCentral firewall policy (AWS Firewall Manager, GCP hierarchical policies, Azure Firewall Manager), org-level guardrails, automated drift detection
Zero trust targetIP allow-lists lag behind realityIdentity-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 آزموده شد:

txt
#!/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;
    }
}
bash
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 با کد ۱ پس از انتظار ۲ ثانیه).

ExperimentResult
nc -z -w 3 SRV 9999 with an input drop policy3.01 s then exit 1 (silent drop)
Add nft add rule inet filter input tcp dport 9999 reject with tcp reset0.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 22exit 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 rule0% 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 شمارهٔ ۱۰۰ گوش دهید:

bash
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 بود.

bash
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:

bash
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 شناخته‌شده کار می‌کنند)، سپس:

bash
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) ​

BeliefReality
NAT is a firewallNAT blocks unsolicited inbound by accident (no table row). RFC 4864: "IPv4 NAT was not developed as a security mechanism"
ufw deny protects Docker published portsDocker's DNAT sends them through FORWARD; ufw owns INPUT. Use 127.0.0.1: binds or DOCKER-USER
A NetworkPolicy always restricts trafficOnly if the CNI enforces it; otherwise "no effect"
Security groups and NACLs are the sameSG: stateful, allow-only, per ENI. NACL: stateless, ordered allow and deny, per subnet
Stateful firewalls need rules for repliesReplies match the tracked flow; stateless ones (NACL) need an ephemeral-port rule
Block all ICMP for safetyDestination unreachable and Packet Too Big make PMTUD work; blocking them causes black holes
iptables and nftables are separate firewallsUsually the same kernel engine; iptables-nft writes nftables rules
DROP is better than REJECT everywhereDROP hides ports from scanners but slows legitimate failures; use REJECT internally
Closing a port in the firewall stops the process listeningThe socket still exists; any other path can reach it. Bind to loopback too
IPv6 is covered by my IPv4 rulesSeparate rules or an inet table are required; with no NAT every host is reachable
A rate limit after the established rule limits pingsAfter the first reply, later echo requests are ESTABLISHED and skip it; place guards earlier
Source-IP allow-lists are authenticationAddresses are shared (CGNAT, proxies, VPN) and spoofable behind trustProxies('*'); combine with identity
NetworkPolicy has deny rules and orderingIt is allow-only and additive; use CNI extensions for deny
Egress does not matter if ingress is lockedCompromise starts outbound: downloads, reverse shells, exfiltration

چکیده (Cheat sheet) ​

TopicWhat to remember
Rule inputs5-tuple, interface, direction, conntrack state; clouds add tags, SG references, labels
Stateless vs statefulStateful (conntrack, SG, NSG, NetworkPolicy): replies free. Stateless (NACL): allow both directions
Default posturepolicy drop; established first, then specifics; keep your SSH rule in before enabling
Hooksprerouting, input, forward, output, postrouting; own packets: input/output; routed (containers): forward
Tablesraw (notrack), mangle, nat (first packet only), filter (verdicts)
Prioritiesraw -300, mangle -150, DNAT -100, filter 0, SNAT 100
iptablesiptables -S, -L -n -v --line-numbers, iptables-save, -A/-I/-D, -m conntrack --ctstate
nftablesnft 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
Logginglimit rate + log; log group N + tcpdump -i nflog:N; counters for volume
ICMPAllow dest-unreachable, time-exceeded, packet-too-big, NDP; rate-limit echo
IPv6No 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
KubernetesDefault allow; default-deny + allow-DNS; AND within an item, OR between items; the CNI enforces
AWSSG: ENI, stateful, allow-only, SG references. NACL: subnet, stateless, numbered, ephemeral 1024-65535
GCP / AzureGCP priority 0-65535 (default 1000), tags; Azure priority 100-4096, defaults at 65000-65500
EgressAllow-list destinations; NAT gateway + domain filtering; Cilium toFQDNs; egress gateway for stable IPs
Listener binding127.0.0.1 or a Unix socket for anything that is not public on purpose
Auditnft 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) ​

TermMeaning
FirewallRules that accept or drop packets or flows by header fields and state
Packet filterA firewall that reads L3-L4 headers only
5-tupleSource IP, source port, destination IP, destination port, protocol
StatelessEvery packet is judged alone; replies need their own rules
StatefulFlows are tracked; replies of an allowed flow pass automatically
Default-deny / allow-listPolicy drop, then list what is allowed
Policy (chain policy)Verdict for packets that match no rule in a base chain
netfilterThe Linux kernel framework of packet hooks that iptables and nftables use
HookA point in the packet path: prerouting, input, forward, output, postrouting (and ingress)
TableA container of chains: iptables filter, nat, mangle, raw; nftables tables you name
ChainAn ordered list of rules; base chains attach to hooks
Base chainAn nftables chain with type, hook, priority
PriorityOrder among chains at one hook; lower number runs first
Verdictaccept, drop, reject, jump, return
iptablesThe classic command-line tool for netfilter rules
iptables-nftiptables syntax over the nftables backend
nftables / nftThe modern rule engine and its tool
Family (ip, ip6, inet, arp, bridge, netdev)Which protocols a table sees
Set / map / concatenationnftables data structures: list of values, key-to-value lookup, pairs
Meter / dynamic setA set filled from traffic, with per-element rate limits
conntrackThe kernel's connection-tracking table
ct stateConnection state: new, established, related, invalid, untracked
ESTABLISHED,RELATEDStates for replies and flows tied to an existing flow (ICMP errors, FTP data)
ctorigdstportconntrack match on the destination port before DNAT
notrackRaw-table action that skips conntrack
DNAT / SNAT / MASQUERADEDestination, source and dynamic-source address rewriting
REJECT vs DROPAnswer with an error vs silently discard
LOG / NFLOGWrite a matched packet to the kernel log or to a userspace group
ufwUbuntu's front-end for netfilter
firewalldZone-based firewall daemon with nftables backend
fail2ban / CrowdSecTools that turn log patterns into temporary block rules
ICMP / ICMPv6Control protocol for errors and diagnostics (and NDP in IPv6)
PMTUDPath MTU Discovery: finding the smallest MTU on a path using ICMP
MTU black holeA path where oversized packets are dropped and no ICMP reaches the sender
MSS clampingRewriting the TCP MSS so segments fit the path MTU
NDPIPv6 neighbor discovery (ICMPv6 133-137), the ARP replacement
DOCKER-USERiptables chain where user rules run before Docker's own
Published portA container port mapped to a host port with -p
Direct routingSending packets to a container's address instead of a published port
NetworkPolicyKubernetes resource defining allowed pod traffic by label, namespace or CIDR
CNIContainer Network Interface plugin that implements pod networking and enforces policy
Calico, CiliumCNIs that enforce NetworkPolicy (iptables or eBPF datapath)
eBPFIn-kernel programs used by Cilium for policy and load balancing
ipBlockNetworkPolicy peer defined by a CIDR
Security groupAWS stateful, allow-only firewall attached to a network interface
Network ACL (NACL)AWS stateless, ordered, allow-and-deny firewall attached to a subnet
ENIElastic Network Interface: the virtual NIC an SG is attached to
Ephemeral portsShort-lived client-side ports (1024-65535 in AWS guidance) used for replies
Prefix listA named set of CIDRs reusable across rules
VPC Flow LogsPer-flow records with ACCEPT or REJECT
GCP firewall ruleVPC-level rule with priority, direction, tags or service accounts
Azure NSGNetwork security group with priorities 100-4096
Service tag / ASGAzure label for a service's prefixes / for a group of VMs
Egress controlRestricting outbound connections
NAT gatewayManaged SNAT for private subnets
Egress gatewayA fixed exit point for pod traffic
FQDN ruleRule that allows a domain name, resolved to addresses by the enforcer
Host firewallRules on the machine itself
PerimeterRules at the edge of a network, subnet or instance
WAFWeb application firewall: L7 filtering of HTTP content
Defense in depthSeveral independent controls so one mistake is not a breach
TrustProxiesLaravel middleware that decides which proxies' X-Forwarded-* headers to believe
Unix domain socketA local socket addressed by a file path

منابع (References) ​

هر URL با curl fetch شد و متنش زیر scratchpad/sources/firewalls-iptables-nftables-security-groups/ ذخیره شد؛ کد HTTP جز مواردی که ذکر شده ۲۰۰ بود.

ساخته‌شده توسط Morteza Negahi