An ninh mạngNetwork Security
Thuộc bộ kiến thức Network Engineer Roadmap.
Tổng quan
Network security (an ninh mạng) là tập hợp các policy, control, kiến trúc và công nghệ nhằm bảo vệ tính bí mật (confidentiality), tính toàn vẹn (integrity) và tính sẵn sàng (availability) của dữ liệu khi nó di chuyển trên mạng và khi lưu trữ. Với một network engineer, bảo mật không phải là một tính năng gắn thêm về sau — nó là một thuộc tính thiết kế mà bạn đưa vào ngay từ addressing plan, routing, switching, segmentation và cấu hình của từng thiết bị.
Note này được viết theo góc nhìn phòng thủ (defensive). Mục tiêu là hiểu các cuộc tấn công đủ sâu để phát hiện (detect) và ngăn chặn (prevent) chúng, cũng như thiết kế mạng “fail safe” — chứ không phải để thực hiện tấn công. Ở mọi chỗ mô tả một cuộc tấn công, trọng tâm luôn là detection và mitigation.
Note này bao gồm:
- Nền tảng bảo mật: CIA triad, defense-in-depth, least privilege, segmentation và DMZ.
- Firewall: packet-filtering (stateless), stateful inspection, circuit-level gateway, application-layer/proxy firewall, và Next-Generation Firewall (NGFW) — kèm bảng so sánh.
- ACL: standard vs extended, direction, thứ tự rule, implicit deny — kèm ví dụ cấu hình Cisco.
- IDS vs IPS: signature vs anomaly detection, inline vs passive, NIDS vs HIDS.
- Cloud security group & NACL (tóm tắt — chi tiết ở ./16-cloud-networking.md).
- Zero-Trust Architecture (ZTA): “never trust, always verify”, microsegmentation, identity-based access, BeyondCorp/ZTNA.
- Kiến thức cơ bản về encryption cho network engineer: symmetric vs asymmetric, TLS/IPsec ở mức tổng quan (chi tiết ở ./12-vpn-and-tunneling.md), MACsec.
- Các cuộc tấn công mạng phổ biến và cách phòng thủ: DoS/DDoS, spoofing, MITM, ARP poisoning, VLAN hopping.
Bảo mật phụ thuộc rất nhiều vào một addressing/subnetting plan chính xác (./05-ip-addressing-and-subnetting.md), vì segmentation, ACL và firewall rule đều được biểu diễn theo subnet. Nếu muốn hệ thống hóa kiến thức này, CompTIA Security+ là certification đầu vào tự nhiên — xem ./18-certifications-and-learning-path.md.
Kiến thức nền tảng
CIA triad
Mọi security control cuối cùng đều phục vụ một hoặc nhiều trong ba mục tiêu:
| Thuộc tính | Trả lời câu hỏi | Ví dụ trên mạng |
|---|---|---|
| Confidentiality (bí mật) | Chỉ bên được phép mới đọc được dữ liệu? | Encryption (TLS, IPsec, MACsec), ACL, VLAN segmentation, access control |
| Integrity (toàn vẹn) | Dữ liệu có bị thay đổi khi truyền/lưu trữ không? | HMAC/chữ ký số, TLS integrity, IPsec AH/ESP, checksum, anti-spoofing filter |
| Availability (sẵn sàng) | Dịch vụ có truy cập được khi cần không? | DDoS mitigation, redundancy, rate limiting, QoS, load balancing |
Một mở rộng phổ biến bổ sung Authentication, Authorization, Accounting (AAA) và non-repudiation. Mọi quyết định thiết kế đều có thể truy về một trong các thuộc tính này — nếu một control không phục vụ thuộc tính nào, hãy đặt câu hỏi vì sao nó tồn tại.
Defense-in-depth
Defense-in-depth nghĩa là xếp lớp nhiều control độc lập, sao cho việc một lớp bị lỗi hoặc bị vượt qua không làm sụp đổ toàn hệ thống. Kẻ tấn công vượt qua được perimeter firewall vẫn còn phải đối mặt với segmentation, host firewall, IDS/IPS, authentication và encryption.
- Lớp 1Perimeter firewall / edge router ACLEdge / NGFW hướng ra Internet — + DDoS protection, anti-spoofing (BCP38)
- Lớp 2DMZ cho dịch vụ publicweb, mail, reverse proxy
- Lớp 3Internal segmentation firewall / VLAN ACLbảo vệ internal core
- Lớp 4Control theo segment, NAC, 802.1Xsegment Users và Servers
- Lớp 5Host firewall, EDR, IDS/IPS
- Lớp 6Encryption, IAM, MFA, logging
Không lớp nào được tin là hoàn hảo. Đây là điều ngược lại với mô hình cũ “vỏ cứng, ruột mềm” (hard shell, soft center), nơi một perimeter mạnh bảo vệ một mạng nội bộ phẳng và được tin tưởng hoàn toàn.
Least privilege
Least privilege (đặc quyền tối thiểu) chỉ cấp cho mỗi user, device và service đúng mức truy cập cần thiết để làm việc — không hơn. Trên mạng, điều này được dịch thành:
- ACL và firewall rule chỉ cho phép đúng protocol/port giữa đúng các subnet cần đến nhau, rồi deny tất cả phần còn lại (default-deny).
- Management plane (SSH, SNMP, GUI thiết bị) chỉ giới hạn trong một management VLAN riêng và các jump host.
- Service account bị giới hạn theo host và port cụ thể.
Network segmentation
Segmentation chia mạng thành các zone cô lập, để một sự cố ở zone này không thể lan tự do (“lateral movement”) sang zone khác. Các kỹ thuật:
- VLAN — segmentation ở Layer 2 trong switch fabric.
- Subnet + ACL/firewall — segmentation ở Layer 3 với chính sách áp dụng giữa các zone.
- Microsegmentation — segmentation rất mịn, thường ở mức từng workload, được thực thi bởi host firewall hoặc SDN policy (một kỹ thuật cốt lõi của Zero-Trust).
Các zone điển hình: user VLAN, server VLAN, voice VLAN, guest/BYOD, IoT/OT, management và DMZ. Traffic giữa các zone phải đi qua một điểm thực thi chính sách (firewall hoặc thiết bị L3 có ACL).
DMZ (Demilitarized Zone)
DMZ là một segment bán tin cậy nằm giữa Internet không tin cậy và mạng nội bộ được tin cậy. Nó chứa các dịch vụ cần truy cập được từ bên ngoài — web server, reverse proxy, mail gateway, DNS. Nếu một host trong DMZ bị chiếm, kẻ tấn công vẫn bị ngăn cách với mạng nội bộ bởi lớp firewall thứ hai.
Internet ── Firewall A ── DMZ (web, mail, DNS) ── Firewall B ── Internal LAN
Nguyên tắc:
- Internet → DMZ: chỉ cho phép đúng dịch vụ public đã công bố (ví dụ 443).
- DMZ → Internal: mặc định deny; chỉ mở đúng luồng cần thiết (ví dụ web server → đúng port DB).
- Internal → DMZ / Internet: được kiểm soát bằng policy, thường qua proxy.
Khái niệm chính
Firewall
Firewall thực thi một security policy lên traffic đi qua một ranh giới, cho phép hoặc từ chối các luồng dựa trên rule. Firewall đã tiến hóa qua nhiều thế hệ, từ packet filter đơn giản đến NGFW nhận biết ngữ cảnh.
Packet-filtering (stateless) firewall
Hoạt động ở Layer 3/4. Nó kiểm tra từng packet một cách độc lập dựa trên rule tĩnh (source/destination IP, protocol, port, flag). Nó không giữ state, nên không biết một packet có thuộc một connection đã thiết lập hay không — bạn phải viết rule tường minh cho cả hai chiều. Nhanh và rẻ, nhưng thô.
Stateful inspection firewall
Duy trì một state table của các connection đang hoạt động. Khi một host nội bộ khởi tạo connection, firewall ghi lại và tự động cho phép traffic trả về tương ứng, đồng thời drop các packet inbound không mời mà không khớp session nào. Đây là baseline cho gần như mọi firewall hiện đại.
Circuit-level gateway
Hoạt động ở session layer (L5). Nó kiểm tra TCP handshake và giám sát tính hợp lệ của session, rồi chuyển tiếp traffic mà không kiểm tra payload. SOCKS proxy là ví dụ kinh điển. Nhẹ nhưng không có khả năng nhìn vào nội dung ứng dụng.
Application-layer / proxy firewall
Hoạt động ở Layer 7 và kết thúc (terminate) connection thay cho client, đóng vai trò trung gian. Nó hiểu các protocol cụ thể (HTTP, FTP, DNS, SMTP), có thể inspect và filter nội dung, ẩn cấu trúc nội bộ và ép đúng protocol. Latency cao hơn và tốn tài nguyên hơn.
Next-Generation Firewall (NGFW)
Kết hợp stateful inspection với:
- Deep Packet Inspection (DPI) — kiểm tra payload của packet, không chỉ header.
- Application awareness — nhận diện ứng dụng bất kể port (ví dụ nhận ra traffic trên 443 thực chất là app chia sẻ file).
- IPS tích hợp — signature-based intrusion prevention chạy inline.
- Threat intelligence & reputation feed — chặn IP/domain/URL đã biết là độc hại.
- Tích hợp user-identity (qua directory service) và TLS/SSL inspection.
Bảng so sánh các loại firewall
| Loại | OSI layer | Stateful? | Inspect payload? | App awareness | Điểm mạnh | Điểm yếu |
|---|---|---|---|---|---|---|
| Packet-filtering (stateless) | L3–L4 | Không | Không | Không | Nhanh, đơn giản, rẻ | Thô, không có session context, dễ misconfig |
| Stateful inspection | L3–L4 | Có | Không | Không | Theo dõi session, chặn inbound không mời | Không thấy L7 |
| Circuit-level gateway | L5 | Có (session) | Không | Không | Kiểm tra session nhẹ | Không inspect nội dung |
| Application-layer / proxy | L7 | Có | Có | Theo protocol | Filter nội dung sâu, ẩn nội bộ | Latency, theo từng protocol, nặng tài nguyên |
| Next-Generation (NGFW) | L3–L7 | Có | Có (DPI) | Có | Nhận biết app/user/threat-intel, IPS tích hợp | Chi phí, phức tạp, TLS-inspection gây lo ngại privacy |
Access Control List (ACL)
ACL là một danh sách có thứ tự các rule permit/deny áp lên interface của router/switch hoặc zone của firewall. Trên Cisco IOS có hai loại chính:
- Standard ACL (số 1–99, 1300–1999): filter chỉ theo source IP. Đặt gần destination (vì nó không phân biệt được loại traffic, đặt gần source sẽ chặn quá mức).
- Extended ACL (số 100–199, 2000–2699, hoặc named): filter theo source và destination IP, protocol và port. Đặt gần source để drop traffic không mong muốn sớm.
Các quy tắc quan trọng về hành vi ACL:
- Direction quan trọng — ACL được áp
inhoặcouttrên interface, tính theo góc nhìn của router. Luôn suy luận từ góc nhìn của router. - Thứ tự quan trọng — rule được duyệt từ trên xuống; rule khớp đầu tiên thắng và dừng xử lý. Đặt rule cụ thể trước rule tổng quát.
- Implicit deny — mọi ACL kết thúc bằng một
deny anyvô hình. Nếu không khớp gì, packet bị drop. Luôn có mộtpermittường minh cho traffic bạn muốn.
Ví dụ ACL trên Cisco
Standard named ACL — chỉ cho phép management subnet truy cập VTY (SSH) của router:
ip access-list standard MGMT-ONLY
permit 10.10.99.0 0.0.0.255
deny any log
!
line vty 0 4
access-class MGMT-ONLY in
transport input ssh
Extended named ACL — policy inbound ở Internet edge trên outside interface:
ip access-list extended INTERNET-IN
! Cho phép traffic trả về của connection đã thiết lập
permit tcp any any established
! Chỉ publish web server DMZ trên 443
permit tcp any host 203.0.113.10 eq 443
! Cho phép DNS inbound tới resolver DMZ
permit udp any host 203.0.113.11 eq 53
! Anti-spoofing: drop packet giả mạo source là dải nội bộ của ta (BCP38)
deny ip 10.0.0.0 0.255.255.255 any log
deny ip 172.16.0.0 0.15.255.255 any log
deny ip 192.168.0.0 0.0.255.255 any log
! Deny tường minh có log (ghi lại implicit deny)
deny ip any any log
!
interface GigabitEthernet0/0
description ** Internet uplink **
ip access-group INTERNET-IN in
Lưu ý wildcard mask (nghịch đảo của subnet mask): 0.0.0.255 khớp một /24. Xem ./05-ip-addressing-and-subnetting.md để nắm phần tính toán.
Kỷ luật default-deny cũng áp dụng cho host Linux. Ví dụ inbound với nftables (hiện đại):
table inet filter {
chain input {
type filter hook input priority 0; policy drop; # default-deny
ct state established,related accept # traffic trả về (stateful)
iif "lo" accept # loopback
tcp dport 22 ip saddr 10.10.99.0/24 accept # SSH chỉ từ mgmt subnet
tcp dport 443 accept # HTTPS public
ct state invalid drop
ip protocol icmp icmp type echo-request limit rate 5/second accept
}
}
Tương đương với iptables:
iptables -P INPUT DROP # default-deny
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp -s 10.10.99.0/24 --dport 22 -j ACCEPT # SSH chỉ từ mgmt
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
IDS vs IPS
Intrusion Detection System (IDS) giám sát traffic và cảnh báo (alert) khi thấy hoạt động khả nghi. Intrusion Prevention System (IPS) nằm inline và có thể chặn (block) traffic độc hại theo thời gian thực.
Phương pháp phát hiện:
- Signature-based — so khớp traffic với cơ sở dữ liệu mẫu tấn công đã biết. Chính xác với threat đã biết, ít false positive, nhưng mù trước tấn công mới (zero-day) và cần cập nhật signature liên tục.
- Anomaly-based (behavioral) — xây dựng baseline “bình thường” và cảnh báo khi có sai lệch. Có thể bắt được tấn công chưa biết nhưng dễ false positive và cần tinh chỉnh (tuning).
Phạm vi triển khai:
- NIDS/NIPS (network-based) — giám sát một segment mạng, thường qua SPAN/mirror port (IDS) hoặc inline (IPS).
- HIDS/HIPS (host-based) — chạy trên endpoint, thấy file, process và system call cục bộ bên cạnh traffic của host đó.
| Khía cạnh | IDS | IPS |
|---|---|---|
| Vị trí | Passive / out-of-band (SPAN, TAP) | Inline (nằm trên đường đi của traffic) |
| Hành động | Phát hiện & cảnh báo | Phát hiện, cảnh báo & chặn/drop |
| Ảnh hưởng tới traffic | Không (không ảnh hưởng luồng) | Thêm latency; lỗi có thể gián đoạn traffic |
| Rủi ro false positive | Bỏ sót cảnh báo | Chặn nhầm traffic hợp lệ |
| Dùng điển hình | Forensics, visibility, monitoring | Bảo vệ chủ động ở perimeter/biên segment |
Engine phát hiện: signature vs anomaly (như trên) — áp dụng cho cả IDS và IPS. Các engine mã nguồn mở phổ biến gồm Snort, Suricata (NIDS/NIPS) và Zeek (network security monitoring). NGFW hiện đại nhúng sẵn chức năng IPS.
Cloud security group & NACL
Trong môi trường cloud, mô hình firewall được chia thành hai lớp (thuật ngữ AWS; các provider khác tương tự):
| Control | Phạm vi | Stateful? | Rule |
|---|---|---|---|
| Security Group (SG) | Instance / ENI (như host firewall) | Stateful — traffic trả về tự động được cho phép | Chỉ có allow rule; implicit deny |
| Network ACL (NACL) | Ranh giới subnet | Stateless — phải allow tường minh cả hai chiều | Có cả allow và deny rule, duyệt theo số thứ tự |
Vì SG là stateful, bạn chỉ cần định nghĩa rule inbound (hoặc outbound) và phản hồi được cho phép tự động. NACL là stateless như packet filter cổ điển, nên bạn phải mở port trả về ephemeral một cách tường minh. Đây chỉ là tóm tắt — nội dung đầy đủ (SG, NACL, thiết kế VPC, cloud NAT, private endpoint) ở ./16-cloud-networking.md.
Zero-Trust Architecture (ZTA)
Zero Trust thay thế mô hình lấy perimeter làm trung tâm bằng nguyên tắc “never trust, always verify” (không bao giờ tin, luôn xác minh). Không user, device hay vị trí mạng nào được tin ngầm — mọi yêu cầu truy cập đều được authenticate, authorize và encrypt, bất kể nó xuất phát từ trong hay ngoài mạng công ty.
Các nguyên lý cốt lõi (NIST SP 800-207):
- Verify explicitly — authenticate và authorize mọi yêu cầu dựa trên identity, device posture, vị trí và hành vi.
- Least-privilege access — cấp quyền just-in-time, just-enough theo từng session.
- Assume breach — segment quyết liệt, encrypt mọi thứ, log và inspect liên tục.
Các cơ chế chính:
- Microsegmentation — cô lập theo từng workload để chặn lateral movement ngay cả bên trong một subnet “được tin cậy”.
- Identity-based access — quyền truy cập gắn với identity mạnh (MFA, device certificate) thay vì địa chỉ IP hay vị trí mạng.
- Policy Enforcement Point (PEP) + Policy Decision Point (PDP) — một broker đánh giá từng yêu cầu theo policy trước khi cấp quyền truy cập tài nguyên.
- ZTNA (Zero-Trust Network Access) — thay quyền VPN rộng bằng tunnel nhận biết identity, theo từng ứng dụng. BeyondCorp của Google là triển khai kinh điển.
So với mô hình cũ: một VPN truyền thống, khi đã kết nối, thường đặt user vào một mạng phẳng được tin cậy. ZTNA thay vào đó môi giới quyền truy cập tới từng ứng dụng và không bao giờ để lộ toàn mạng. Cơ chế VPN được trình bày ở ./12-vpn-and-tunneling.md.
Kiến thức cơ bản về encryption cho network engineer
Encryption bảo vệ confidentiality (và, kèm authentication, integrity) của dữ liệu khi truyền và khi lưu trữ.
- Symmetric encryption — cùng một khóa bí mật để encrypt và decrypt (AES, ChaCha20). Nhanh; dùng cho dữ liệu khối lượng lớn. Thách thức: phân phối khóa chia sẻ một cách an toàn.
- Asymmetric encryption — một cặp public/private key liên kết toán học (RSA, ECDSA, ECDH). Gì được encrypt bằng public key chỉ có thể decrypt bằng private key, và ngược lại cho chữ ký. Chậm hơn; dùng để trao đổi khóa symmetric và để authenticate.
Các protocol thực tế kết hợp cả hai: crypto asymmetric thực hiện authentication và key exchange, rồi một cipher symmetric nhanh bảo vệ dữ liệu thực.
| Protocol | Layer | Bảo vệ | Dùng điển hình |
|---|---|---|---|
| TLS | L4–L7 (trên TCP/UDP) | Session ứng dụng | HTTPS, email bảo mật, API |
| IPsec | L3 | Packet IP | VPN site-to-site và remote-access |
| MACsec (802.1AE) | L2 | Ethernet frame trên một link | Mã hóa link switch-to-switch/host-to-switch trong LAN/DC |
- TLS encrypt traffic ứng dụng và authenticate server (và tùy chọn cả client) qua certificate. Là nền tảng của HTTPS.
- IPsec bảo vệ traffic IP với AH (integrity/authentication) và ESP (encryption + integrity), ở transport hoặc tunnel mode — trụ cột của VPN.
- MACsec cung cấp encryption hop-by-hop ở Layer 2, bảo vệ traffic giữa các thiết bị kết nối trực tiếp ngay cả trước khi nó chạm ranh giới lớp IP.
TLS và IPsec được trình bày chi tiết ở ./12-vpn-and-tunneling.md.
Các cuộc tấn công mạng phổ biến — và cách phòng thủ
Phần dưới đây mang tính phòng thủ: mỗi cuộc tấn công là gì và cách phát hiện, giảm thiểu. Cố tình không phải là hướng dẫn thực hiện tấn công.
DoS / DDoS (Denial of Service / Distributed DoS)
Là gì: các nỗ lực làm cạn kiệt tài nguyên của mục tiêu để người dùng hợp lệ không được phục vụ. DDoS dùng nhiều nguồn phân tán (thường là botnet). Ba nhóm lớn:
- Volumetric — làm bão hòa băng thông (ví dụ reflection/amplification flood).
- Protocol / state-exhaustion — làm cạn connection table hoặc state của thiết bị (ví dụ SYN flood).
- Application-layer (L7) — làm cạn tài nguyên server bằng các request trông có vẻ hợp lệ (ví dụ HTTP flood).
Phòng thủ / mitigation:
- Rate limiting và connection limit ở edge; SYN cookie để chịu được SYN flood.
- Upstream scrubbing — định tuyến traffic qua một nhà cung cấp DDoS-mitigation/scrubbing để lọc traffic tấn công và chuyển tiếp traffic sạch.
- Anycast — quảng bá dịch vụ từ nhiều vị trí để traffic volumetric bị hấp thụ và phân tán trên một mạng lớn.
- CDN / WAF đặt trước web app để hấp thụ và lọc L7 flood.
- Overprovisioning và autoscaling để có headroom; BCP38 anti-spoofing ở ingress để giảm lạm dụng reflection.
- Blackhole / RTBH routing như biện pháp cuối cùng để drop traffic tới một IP bị nhắm.
Spoofing
Là gì: giả mạo một identity nguồn — IP spoofing (giả source IP), MAC spoofing, DNS spoofing, hoặc email spoofing — để giả danh một thực thể tin cậy hoặc né filter.
Phòng thủ:
- Ingress/egress filtering (BCP38/uRPF) — drop packet có source address không thể đến hợp lệ trên interface đó.
- DHCP snooping + Dynamic ARP Inspection (DAI) + IP Source Guard trên switch để ràng buộc IP/MAC/port.
- DNSSEC để authenticate DNS response; SPF/DKIM/DMARC cho email.
- Authenticate ở tầng ứng dụng — không bao giờ tin một địa chỉ IP như là identity.
MITM (Man-in-the-Middle)
Là gì: kẻ tấn công lén chuyển tiếp/thay đổi traffic giữa hai bên đang tin rằng họ giao tiếp trực tiếp.
Phòng thủ:
- Encryption mạnh kèm validate certificate — TLS với kiểm tra cert đúng cách, HSTS, và pinning khi phù hợp sẽ vô hiệu hóa nghe lén thụ động và phát hiện can thiệp.
- Mutual authentication (mTLS, IPsec với IKE mạnh).
- Bảo vệ ở switch (DAI, DHCP snooping) để ngăn các chuyển hướng L2 mà MITM thường dựa vào.
- Tránh mạng không tin cậy hoặc tunnel qua VPN (./12-vpn-and-tunneling.md).
ARP poisoning / ARP spoofing
Là gì: vì ARP cổ điển không có authentication, kẻ tấn công cùng segment L2 có thể gửi ARP reply giả để gán MAC của mình với IP của host khác (thường là gateway), tạo điều kiện cho MITM hoặc DoS.
Phòng thủ:
- Dynamic ARP Inspection (DAI) — kiểm tra ARP packet dựa trên bảng binding của DHCP snooping và drop gói giả.
- DHCP snooping làm nguồn tin cậy cho DAI; IP Source Guard.
- Static ARP entry cho các host quan trọng trong môi trường nhỏ/nhạy cảm.
- Port security để giới hạn số MAC trên mỗi port; segment broadcast domain để thu nhỏ blast radius.
VLAN hopping
Là gì: đưa frame vào một VLAN mà kẻ tấn công không nên chạm tới, qua switch spoofing (thương lượng trunk) hoặc double-tagging (lồng hai tag 802.1Q).
Phòng thủ:
- Tắt DTP / auto-trunking — đặt access port thành
switchport mode accessvàswitchport nonegotiate. - Đổi native VLAN trên trunk sang một VLAN chuyên dụng không dùng và không bao giờ mang traffic user trên đó — điều này vô hiệu hóa double-tagging.
- Chỉ allow tường minh các VLAN cần thiết trên trunk (
switchport trunk allowed vlan). - Đặt các port không dùng vào một VLAN “parking”/shutdown và disable chúng về mặt hành chính.
Ví dụ hardening access-port trên Cisco:
interface range GigabitEthernet0/1 - 24
switchport mode access
switchport access vlan 20
switchport nonegotiate
spanning-tree portfast
spanning-tree bpduguard enable
switchport port-security
switchport port-security maximum 2
switchport port-security violation restrict
Best Practices
- Default-deny ở mọi nơi. ACL, firewall rule, security group và NACL chỉ nên cho phép đúng cái cần thiết và drop phần còn lại. Dựa vào implicit deny, nhưng có log.
- Segment quyết liệt. Tách user, server, management, guest, IoT/OT và DMZ. Thực thi policy giữa các zone tại firewall hoặc L3 ACL. Tiến dần tới microsegmentation.
- Bảo vệ management plane. Chỉ SSH (không bao giờ Telnet), trên một management VLAN riêng, giới hạn bằng ACL tới jump host, kèm MFA và AAA mạnh (TACACS+/RADIUS). Tắt các service không dùng.
- Áp least privilege cho mọi user, device và service account.
- Hardening Layer 2. Bật DHCP snooping, Dynamic ARP Inspection, IP Source Guard, port security, BPDU guard; tắt auto-trunking; đặt native VLAN chuyên dụng.
- Anti-spoofing ở edge. Triển khai BCP38 ingress/egress filtering và uRPF.
- Xếp lớp detection với prevention. Kết hợp IPS/NGFW inline với IDS/monitoring out-of-band (Suricata/Zeek) và logging tập trung (SIEM).
- Encrypt khi truyền. TLS cho ứng dụng, IPsec cho VPN, MACsec cho link nhạy cảm. Validate certificate; tắt cipher yếu và phiên bản protocol cũ.
- Lên kế hoạch cho DDoS trước khi cần: upstream scrubbing, CDN/WAF, anycast, rate limiting và một runbook.
- Log, monitor và alert. Bạn không thể phòng thủ cái bạn không thấy. Tập trung log, xây baseline bình thường, và cảnh báo khi có anomaly.
- Patch và cập nhật signature firewall/IPS, firmware thiết bị và threat-intel feed thường xuyên.
- Áp dụng nguyên lý Zero-Trust từng bước: identity mạnh + MFA, device posture, per-application access (ZTNA), segmentation theo tư duy assume-breach.
- Kiểm thử và audit. Rà soát cấu hình định kỳ, dọn rule (xóa entry ACL/firewall cũ), và pentest có ủy quyền.
- Tài liệu hóa. Mỗi ACL và firewall rule nên có comment/remark giải thích mục đích và chủ sở hữu.
Tài liệu tham khảo
- NIST SP 800-207 — Zero Trust Architecture
- NIST SP 800-41 Rev.1 — Guidelines on Firewalls and Firewall Policy
- OWASP — Network Segmentation Cheat Sheet
- Cloudflare Learning — What is network security?
- Cloudflare Learning — DDoS attacks and mitigation
- Cisco — Configuring IP Access Lists
- Google BeyondCorp — A New Approach to Enterprise Security
- BCP38 / RFC 2827 — Network Ingress Filtering
Part of the Network Engineer Roadmap knowledge base.
Overview
Network security is the collection of policies, controls, architectures, and technologies that protect the confidentiality, integrity, and availability of data as it moves across and rests on a network. For a network engineer, security is not a bolt-on feature that a separate team adds later — it is a design property that you bake into addressing plans, routing, switching, segmentation, and every device configuration.
This note is written from a defensive point of view. The goal is to understand attacks well enough to detect and prevent them and to design networks that fail safely — not to perform them. Everywhere an attack is described, the emphasis is on detection and mitigation.
This note covers:
- Security fundamentals: the CIA triad, defense-in-depth, least privilege, segmentation, and the DMZ.
- Firewalls: packet-filtering (stateless), stateful inspection, circuit-level gateways, application-layer/proxy firewalls, and the Next-Generation Firewall (NGFW) — with a comparison table.
- ACLs: standard vs extended, direction, rule ordering, implicit deny — with Cisco configuration examples.
- IDS vs IPS: signature vs anomaly detection, inline vs passive, NIDS vs HIDS.
- Cloud security groups & NACLs (briefly — deep dive in ./16-cloud-networking.md).
- Zero-Trust Architecture (ZTA): “never trust, always verify”, microsegmentation, identity-based access, BeyondCorp/ZTNA.
- Encryption basics for the network engineer: symmetric vs asymmetric, TLS/IPsec at a glance (deep dive in ./12-vpn-and-tunneling.md), MACsec.
- Common network attacks and how to defend against them: DoS/DDoS, spoofing, MITM, ARP poisoning, VLAN hopping.
Security depends heavily on a correct addressing and subnetting plan (./05-ip-addressing-and-subnetting.md), because segmentation, ACLs, and firewall rules are all expressed in terms of subnets. If you want to formalize this knowledge, CompTIA Security+ is the natural entry-level certification — see ./18-certifications-and-learning-path.md.
Fundamentals
The CIA triad
Every security control ultimately serves one or more of three goals:
| Property | Question it answers | Network examples |
|---|---|---|
| Confidentiality | Can only authorized parties read the data? | Encryption (TLS, IPsec, MACsec), ACLs, VLAN segmentation, access control |
| Integrity | Has the data been altered in transit or at rest? | HMAC/digital signatures, TLS integrity, IPsec AH/ESP, checksums, anti-spoofing filters |
| Availability | Is the service reachable when needed? | DDoS mitigation, redundancy, rate limiting, QoS, load balancing |
A common extension adds Authentication, Authorization, and Accounting (AAA), and non-repudiation. Every design decision can be traced back to one of these properties — if a control does not serve one, question why it exists.
Defense-in-depth
Defense-in-depth means layering independent controls so that the failure or bypass of any one layer does not compromise the whole system. An attacker who gets past the perimeter firewall still faces segmentation, host firewalls, IDS/IPS, authentication, and encryption.
- Layer 1Perimeter firewall / edge router ACLsEdge / NGFW facing the Internet — + DDoS protection, anti-spoofing (BCP38)
- Layer 2DMZ for public-facing servicesweb, mail, reverse proxy
- Layer 3Internal segmentation firewall / VLAN ACLsguards the internal core
- Layer 4Per-segment controls, NAC, 802.1XUsers and Servers segments
- Layer 5Host firewalls, EDR, IDS/IPS
- Layer 6Encryption, IAM, MFA, logging
No single layer is trusted to be perfect. This is the opposite of the old “hard shell, soft center” model where a strong perimeter protected a flat, fully trusted internal network.
Least privilege
Least privilege grants every user, device, and service only the access it needs to do its job — nothing more. On the network this translates to:
- ACLs and firewall rules that permit only required protocols/ports between only the subnets that need them, then deny everything else (default-deny).
- Management planes (SSH, SNMP, device GUIs) restricted to a dedicated management VLAN and jump hosts.
- Service accounts scoped to specific hosts and ports.
Network segmentation
Segmentation divides a network into isolated zones so that a compromise in one zone cannot freely spread (“lateral movement”) to others. Techniques:
- VLANs — Layer-2 segmentation within a switch fabric.
- Subnets + ACLs/firewalls — Layer-3 segmentation with inter-zone policy enforcement.
- Microsegmentation — very fine-grained, often per-workload segmentation enforced by host firewalls or SDN policy (a core Zero-Trust technique).
Typical zones: user VLANs, server VLANs, voice VLAN, guest/BYOD, IoT/OT, management, and the DMZ. Traffic between zones must pass through a policy enforcement point (firewall or L3 device with ACLs).
The DMZ (Demilitarized Zone)
A DMZ is a semi-trusted network segment that sits between the untrusted Internet and the trusted internal network. It hosts services that must be reachable from the outside — web servers, reverse proxies, mail gateways, DNS. If a DMZ host is compromised, the attacker is still separated from the internal network by a second firewall layer.
Internet ── Firewall A ── DMZ (web, mail, DNS) ── Firewall B ── Internal LAN
Rules of thumb:
- Internet → DMZ: allow only the specific published services (e.g., 443).
- DMZ → Internal: deny by default; allow only tightly scoped flows (e.g., web server → specific DB port).
- Internal → DMZ / Internet: controlled by policy, often via a proxy.
Key Concepts
Firewalls
A firewall enforces a security policy on traffic crossing a boundary, allowing or denying flows based on rules. Firewalls have evolved through several generations, from simple packet filters to context-aware NGFWs.
Packet-filtering (stateless) firewall
Operates at Layer 3/4. It examines each packet in isolation against static rules (source/destination IP, protocol, port, flags). It keeps no state, so it cannot tell whether a packet belongs to an established connection — you must write explicit rules for both directions. Fast and cheap, but coarse.
Stateful inspection firewall
Maintains a state table of active connections. When an internal host initiates a connection, the firewall records it and automatically permits the corresponding return traffic, dropping unsolicited inbound packets that do not match an existing session. This is the baseline for virtually all modern firewalls.
Circuit-level gateway
Operates at the session layer (L5). It validates the TCP handshake and monitors that sessions are legitimate, then relays traffic without inspecting payloads. SOCKS proxies are a classic example. Lightweight but no application-content visibility.
Application-layer / proxy firewall
Operates at Layer 7 and terminates connections on behalf of clients, acting as an intermediary. It understands specific protocols (HTTP, FTP, DNS, SMTP) and can inspect and filter content, hide internal structure, and enforce protocol correctness. Higher latency and more resource-intensive.
Next-Generation Firewall (NGFW)
Combines stateful inspection with:
- Deep Packet Inspection (DPI) — inspects packet payloads, not just headers.
- Application awareness — identifies applications regardless of port (e.g., recognizes that traffic on 443 is really a file-sharing app).
- Integrated IPS — signature-based intrusion prevention inline.
- Threat intelligence & reputation feeds — blocks known-bad IPs/domains/URLs.
- User-identity integration (via directory services) and TLS/SSL inspection.
Firewall types comparison
| Type | OSI layer | Stateful? | Inspects payload? | App awareness | Strengths | Weaknesses |
|---|---|---|---|---|---|---|
| Packet-filtering (stateless) | L3–L4 | No | No | No | Fast, simple, cheap | Coarse, no session context, easy to misconfigure |
| Stateful inspection | L3–L4 | Yes | No | No | Tracks sessions, blocks unsolicited inbound | No L7 visibility |
| Circuit-level gateway | L5 | Yes (session) | No | No | Lightweight session validation | No content inspection |
| Application-layer / proxy | L7 | Yes | Yes | Protocol-specific | Deep content filtering, hides internals | Latency, per-protocol, resource-heavy |
| Next-Generation (NGFW) | L3–L7 | Yes | Yes (DPI) | Yes | App/user/threat-intel aware, integrated IPS | Cost, complexity, TLS-inspection privacy concerns |
Access Control Lists (ACLs)
An ACL is an ordered list of permit/deny rules applied to router/switch interfaces or firewall zones. On Cisco IOS there are two main types:
- Standard ACL (numbered 1–99, 1300–1999): filters on source IP only. Place it close to the destination (because it cannot distinguish traffic types, placing it near the source would over-block).
- Extended ACL (numbered 100–199, 2000–2699, or named): filters on source and destination IP, protocol, and ports. Place it close to the source to drop unwanted traffic early.
Key rules of ACL behavior:
- Direction matters — an ACL is applied
inorouton an interface, relative to the router. Always reason from the router’s perspective. - Order matters — rules are evaluated top-down; the first match wins and processing stops. Put specific rules before general ones.
- Implicit deny — every ACL ends with an invisible
deny any. If nothing matches, the packet is dropped. Always include an explicitpermitfor the traffic you want.
Cisco ACL examples
Standard named ACL — allow only the management subnet to reach the router VTY (SSH) lines:
ip access-list standard MGMT-ONLY
permit 10.10.99.0 0.0.0.255
deny any log
!
line vty 0 4
access-class MGMT-ONLY in
transport input ssh
Extended named ACL — an inbound Internet edge policy on the outside interface:
ip access-list extended INTERNET-IN
! Allow established return traffic
permit tcp any any established
! Publish the DMZ web server on 443 only
permit tcp any host 203.0.113.10 eq 443
! Allow inbound DNS to the DMZ resolver
permit udp any host 203.0.113.11 eq 53
! Anti-spoofing: drop packets claiming to be from our internal ranges (BCP38)
deny ip 10.0.0.0 0.255.255.255 any log
deny ip 172.16.0.0 0.15.255.255 any log
deny ip 192.168.0.0 0.0.255.255 any log
! Explicit deny with logging (documents the implicit deny)
deny ip any any log
!
interface GigabitEthernet0/0
description ** Internet uplink **
ip access-group INTERNET-IN in
Note the wildcard masks (inverse of subnet masks): 0.0.0.255 matches a /24. See ./05-ip-addressing-and-subnetting.md for the arithmetic.
The same default-deny discipline applies to Linux hosts. nftables (modern) inbound example:
table inet filter {
chain input {
type filter hook input priority 0; policy drop; # default-deny
ct state established,related accept # stateful return traffic
iif "lo" accept # loopback
tcp dport 22 ip saddr 10.10.99.0/24 accept # SSH from mgmt subnet only
tcp dport 443 accept # public HTTPS
ct state invalid drop
ip protocol icmp icmp type echo-request limit rate 5/second accept
}
}
Equivalent iptables essentials:
iptables -P INPUT DROP # default-deny
iptables -A INPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -p tcp -s 10.10.99.0/24 --dport 22 -j ACCEPT # SSH from mgmt only
iptables -A INPUT -p tcp --dport 443 -j ACCEPT # HTTPS
iptables -A INPUT -m conntrack --ctstate INVALID -j DROP
IDS vs IPS
An Intrusion Detection System (IDS) monitors traffic and alerts on suspicious activity. An Intrusion Prevention System (IPS) sits inline and can block malicious traffic in real time.
Detection methods:
- Signature-based — matches traffic against a database of known attack patterns. Accurate for known threats, low false positives, but blind to novel (zero-day) attacks and needs constant signature updates.
- Anomaly-based (behavioral) — builds a baseline of “normal” and flags deviations. Can catch unknown attacks but is prone to false positives and requires tuning.
Deployment scope:
- NIDS/NIPS (network-based) — monitors a network segment, typically via a SPAN/mirror port (IDS) or inline (IPS).
- HIDS/HIPS (host-based) — runs on an endpoint, sees local files, processes, and system calls in addition to that host’s traffic.
| Aspect | IDS | IPS |
|---|---|---|
| Position | Passive / out-of-band (SPAN, TAP) | Inline (in the traffic path) |
| Action | Detect & alert | Detect, alert, & block/drop |
| Impact on traffic | None (does not affect flow) | Adds latency; a failure can disrupt traffic |
| Risk of false positive | Missed alert | Legitimate traffic blocked |
| Typical use | Forensics, visibility, monitoring | Active protection at the perimeter/segment edge |
Detection engines: signature vs anomaly (as above) — apply to both IDS and IPS. Popular open-source engines include Snort, Suricata (NIDS/NIPS), and Zeek (network security monitoring). Modern NGFWs embed IPS functionality directly.
Cloud security groups & NACLs
In cloud environments the firewall model is split into two layers (AWS terminology; other providers are analogous):
| Control | Scope | Stateful? | Rules |
|---|---|---|---|
| Security Group (SG) | Instance / ENI (like a host firewall) | Stateful — return traffic auto-allowed | Allow rules only; implicit deny |
| Network ACL (NACL) | Subnet boundary | Stateless — must allow both directions explicitly | Allow and deny rules, evaluated in numbered order |
Because SGs are stateful, you only define the inbound (or outbound) rule and the response is permitted automatically. NACLs are stateless like classic packet filters, so you must open ephemeral return ports explicitly. This is only a summary — the full treatment (SGs, NACLs, VPC design, cloud NAT, private endpoints) is in ./16-cloud-networking.md.
Zero-Trust Architecture (ZTA)
Zero Trust replaces the perimeter-centric model with the principle “never trust, always verify.” No user, device, or network location is trusted implicitly — every access request is authenticated, authorized, and encrypted, regardless of whether it originates inside or outside the corporate network.
Core tenets (NIST SP 800-207):
- Verify explicitly — authenticate and authorize every request based on identity, device posture, location, and behavior.
- Least-privilege access — grant just-in-time, just-enough access per session.
- Assume breach — segment aggressively, encrypt everything, log and inspect continuously.
Key mechanisms:
- Microsegmentation — per-workload isolation so that lateral movement is blocked even inside a “trusted” subnet.
- Identity-based access — access is tied to strong identity (MFA, device certificates) rather than IP address or network location.
- Policy Enforcement Point (PEP) + Policy Decision Point (PDP) — a broker evaluates each request against policy before granting access to a resource.
- ZTNA (Zero-Trust Network Access) — replaces broad VPN access with per-application, identity-aware tunnels. Google’s BeyondCorp is the canonical implementation.
Contrast with the legacy model: a traditional VPN, once connected, often places the user on a flat trusted network. ZTNA instead brokers access to individual applications and never exposes the broader network. VPN mechanics are covered in ./12-vpn-and-tunneling.md.
Encryption basics for the network engineer
Encryption protects confidentiality (and, with authentication, integrity) of data in transit and at rest.
- Symmetric encryption — the same secret key encrypts and decrypts (AES, ChaCha20). Fast; used for bulk data. Challenge: securely distributing the shared key.
- Asymmetric encryption — a mathematically linked public/private key pair (RSA, ECDSA, ECDH). Anything encrypted with the public key can only be decrypted with the private key, and vice-versa for signatures. Slower; used to exchange symmetric keys and to authenticate.
Real protocols combine both: asymmetric crypto performs authentication and a key exchange, then a fast symmetric cipher protects the actual data.
| Protocol | Layer | Protects | Typical use |
|---|---|---|---|
| TLS | L4–L7 (over TCP/UDP) | Application sessions | HTTPS, secure email, APIs |
| IPsec | L3 | IP packets | Site-to-site and remote-access VPNs |
| MACsec (802.1AE) | L2 | Ethernet frames on a link | Switch-to-switch/host-to-switch link encryption in the LAN/DC |
- TLS encrypts application traffic and authenticates the server (and optionally the client) via certificates. It is the foundation of HTTPS.
- IPsec secures IP traffic with AH (integrity/authentication) and ESP (encryption + integrity), in transport or tunnel mode — the workhorse of VPNs.
- MACsec provides hop-by-hop encryption at Layer 2, protecting traffic between directly connected devices even before it reaches an IP-layer boundary.
TLS and IPsec are covered in depth in ./12-vpn-and-tunneling.md.
Common network attacks — and how to defend
The following is defensive: what each attack is and how to detect and mitigate it. It is deliberately not a how-to for performing attacks.
DoS / DDoS (Denial of Service / Distributed DoS)
What it is: attempts to exhaust a target’s resources so legitimate users cannot be served. A DDoS uses many distributed sources (often a botnet). Three broad categories:
- Volumetric — saturates bandwidth (e.g., reflection/amplification floods).
- Protocol / state-exhaustion — exhausts connection tables or device state (e.g., SYN floods).
- Application-layer (L7) — exhausts server resources with seemingly legitimate requests (e.g., HTTP floods).
Defense / mitigation:
- Rate limiting and connection limits at the edge; SYN cookies to survive SYN floods.
- Upstream scrubbing — route traffic through a DDoS-mitigation/scrubbing provider that filters attack traffic and forwards clean traffic.
- Anycast — announce the service from many locations so volumetric traffic is absorbed and dispersed across a large distributed network.
- CDN / WAF in front of web apps to absorb and filter L7 floods.
- Overprovisioning and autoscaling for headroom; BCP38 anti-spoofing at ingress to reduce reflection abuse.
- Blackhole / RTBH routing as a last-resort to drop traffic to a targeted IP.
Spoofing
What it is: forging a source identity — IP spoofing (fake source IP), MAC spoofing, DNS spoofing, or email spoofing — to impersonate a trusted entity or evade filters.
Defense:
- Ingress/egress filtering (BCP38/uRPF) — drop packets whose source address could not legitimately arrive on that interface.
- DHCP snooping + Dynamic ARP Inspection (DAI) + IP Source Guard on switches to bind IP/MAC/port.
- DNSSEC to authenticate DNS responses; SPF/DKIM/DMARC for email.
- Authenticate at the application layer — never trust an IP address as identity.
MITM (Man-in-the-Middle)
What it is: an attacker secretly relays/alters traffic between two parties who believe they communicate directly.
Defense:
- Strong encryption with certificate validation — TLS with proper cert checking, HSTS, and pinning where appropriate defeats passive interception and detects tampering.
- Mutual authentication (mTLS, IPsec with strong IKE).
- Switch protections (DAI, DHCP snooping) to prevent the L2 redirections MITM often relies on.
- Avoid untrusted networks or tunnel over a VPN (./12-vpn-and-tunneling.md).
ARP poisoning / ARP spoofing
What it is: because classic ARP has no authentication, an attacker on the same L2 segment can send forged ARP replies to associate their MAC with another host’s IP (often the gateway), enabling MITM or DoS.
Defense:
- Dynamic ARP Inspection (DAI) — validates ARP packets against the DHCP snooping binding table and drops forged ones.
- DHCP snooping as the trust source for DAI; IP Source Guard.
- Static ARP entries for critical hosts in small/sensitive environments.
- Port security to limit MACs per port; segment broadcast domains to shrink the blast radius.
VLAN hopping
What it is: getting frames onto a VLAN the attacker should not reach, via switch spoofing (negotiating a trunk) or double-tagging (nesting two 802.1Q tags).
Defense:
- Disable DTP / auto-trunking — set access ports to
switchport mode accessandswitchport nonegotiate. - Change the native VLAN on trunks to an unused, dedicated VLAN and never carry user traffic on it — this defeats double-tagging.
- Explicitly allow only required VLANs on trunks (
switchport trunk allowed vlan). - Put unused ports in a shutdown/parking VLAN and administratively disable them.
Cisco access-port hardening example:
interface range GigabitEthernet0/1 - 24
switchport mode access
switchport access vlan 20
switchport nonegotiate
spanning-tree portfast
spanning-tree bpduguard enable
switchport port-security
switchport port-security maximum 2
switchport port-security violation restrict
Best Practices
- Default-deny everywhere. ACLs, firewall rules, security groups, and NACLs should permit only what is explicitly required and drop the rest. Rely on the implicit deny, but log it.
- Segment aggressively. Separate users, servers, management, guest, IoT/OT, and DMZ. Enforce inter-zone policy at a firewall or L3 ACL. Move toward microsegmentation.
- Protect the management plane. SSH only (never Telnet), on a dedicated management VLAN, restricted by ACL to jump hosts, with MFA and strong AAA (TACACS+/RADIUS). Disable unused services.
- Apply least privilege to every user, device, and service account.
- Harden Layer 2. Enable DHCP snooping, Dynamic ARP Inspection, IP Source Guard, port security, BPDU guard; disable auto-trunking; set a dedicated native VLAN.
- Anti-spoofing at the edge. Deploy BCP38 ingress/egress filtering and uRPF.
- Layer detection with prevention. Combine an inline IPS/NGFW with out-of-band IDS/monitoring (Suricata/Zeek) and centralized logging (SIEM).
- Encrypt in transit. TLS for applications, IPsec for VPNs, MACsec for sensitive links. Validate certificates; disable weak ciphers and old protocol versions.
- Plan for DDoS before you need to: upstream scrubbing, CDN/WAF, anycast, rate limiting, and a runbook.
- Log, monitor, and alert. You cannot defend what you cannot see. Centralize logs, baseline normal, and alert on anomalies.
- Patch and update firewall/IPS signatures, device firmware, and threat-intel feeds regularly.
- Adopt Zero-Trust principles incrementally: strong identity + MFA, device posture, per-application access (ZTNA), assume-breach segmentation.
- Test and audit. Regular configuration reviews, rule cleanup (remove stale ACL/firewall entries), and authorized penetration tests.
- Document. Every ACL and firewall rule should have a comment/remark explaining its purpose and owner.
References
- NIST SP 800-207 — Zero Trust Architecture
- NIST SP 800-41 Rev.1 — Guidelines on Firewalls and Firewall Policy
- OWASP — Network Segmentation Cheat Sheet
- Cloudflare Learning — What is network security?
- Cloudflare Learning — DDoS attacks and mitigation
- Cisco — Configuring IP Access Lists
- Google BeyondCorp — A New Approach to Enterprise Security
- BCP38 / RFC 2827 — Network Ingress Filtering