Skip to content

netlearn.jsx

File: htb/netlearn.jsx

import React, { useState, useEffect } from 'react';
import { CheckCircle, Circle, ArrowRight, ArrowLeft, Book, Award } from 'lucide-react';

const NetworkingLearner = () => {
  const [currentLesson, setCurrentLesson] = useState(0);
  const [completedLessons, setCompletedLessons] = useState(new Set());
  const [showAnswer, setShowAnswer] = useState(false);
  const [userAnswer, setUserAnswer] = useState('');

  const lessons = [
    {
      id: 0,
      title: "OSI Model Layers",
      category: "Fundamentals",
      content: `The OSI model has 7 layers. You need to know these cold:

**Layer 7 - Application**: HTTP, DNS, SSH, FTP
**Layer 4 - Transport**: TCP, UDP (ports live here)
**Layer 3 - Network**: IP addresses, routing
**Layer 2 - Data Link**: MAC addresses, switches
**Layer 1 - Physical**: Cables, signals

**Why this matters for pentesting:**
- Layer 7: Web app attacks, protocol manipulation
- Layer 4: Port scanning, TCP handshakes
- Layer 3: IP spoofing, routing attacks
- Layer 2: ARP spoofing, MAC flooding

Most of your work happens at L3-L7.`,
      practice: {
        question: "When you run 'nmap -sS target', which OSI layer is primarily being manipulated?",
        options: ["Layer 7", "Layer 4", "Layer 3", "Layer 2"],
        correct: 1,
        explanation: "Layer 4 (Transport). SYN scan manipulates TCP handshake at the transport layer. You send SYN, get SYN-ACK (port open) or RST (closed), never complete the handshake."
      }
    },
    {
      id: 1,
      title: "TCP Three-Way Handshake",
      category: "TCP/IP",
      content: `TCP establishes connections with three packets:

**1. SYN** (Client → Server)
   - "I want to connect"
   - Sets SYN flag, includes initial sequence number

**2. SYN-ACK** (Server → Client)
   - "OK, let's connect"
   - Sets SYN + ACK flags, includes server's sequence number

**3. ACK** (Client → Server)
   - "Connection established"
   - Sets ACK flag

**TCP Flags You Need to Know:**
- SYN: Synchronize (start connection)
- ACK: Acknowledge (confirm receipt)
- FIN: Finish (close connection)
- RST: Reset (abort connection)
- PSH: Push (send data immediately)
- URG: Urgent (priority data)

**Pentesting Relevance:**
- SYN scan (-sS): Send SYN, don't complete handshake (stealthier)
- Full connect (-sT): Complete handshake (shows in logs)
- FIN/NULL/Xmas scans: Send weird flag combos to evade filters`,
      practice: {
        question: "A server responds with RST flag. What does this mean?",
        options: [
          "Port is open and accepting connections",
          "Port is closed/connection rejected",
          "Port is filtered by firewall",
          "Three-way handshake completed"
        ],
        correct: 1,
        explanation: "RST = connection rejected. Port is closed or service refused. Filtered ports typically don't respond at all (timeout) or send ICMP unreachable."
      }
    },
    {
      id: 2,
      title: "IP Addressing & Subnetting",
      category: "TCP/IP",
      content: `**IPv4 Address Structure:**
192.168.1.100 = 32 bits (4 octets × 8 bits)

**CIDR Notation:**
- /24 = 255.255.255.0 = 256 addresses (254 usable)
- /16 = 255.255.0.0 = 65,536 addresses
- /8 = 255.0.0.0 = 16,777,216 addresses

**Private IP Ranges** (RFC 1918):
- 10.0.0.0/8 (Class A)
- 172.16.0.0/12 (Class B)
- 192.168.0.0/16 (Class C)

**Quick Subnet Calculation:**
/24 = last octet for hosts
/16 = last two octets for hosts
/25 = 128 addresses (half of /24)
/26 = 64 addresses
/27 = 32 addresses

**For Pentesting:**
- Internal networks almost always use RFC 1918
- /24 is most common for SMB networks
- Identify network boundaries to pivot correctly
- Calculate broadcast address for ARP scanning`,
      practice: {
        question: "How many usable host addresses in 192.168.1.0/26?",
        options: ["32", "62", "64", "126"],
        correct: 1,
        explanation: "/26 = 64 total addresses. Subtract 2 (network + broadcast) = 62 usable hosts. Formula: 2^(32-26) - 2 = 2^6 - 2 = 62"
      }
    },
    {
      id: 3,
      title: "Common Ports & Services",
      category: "Services",
      content: `**Critical Ports You'll See Constantly:**

**Web:**
- 80/tcp: HTTP
- 443/tcp: HTTPS
- 8080/tcp: HTTP alternate (proxy/testing)
- 8443/tcp: HTTPS alternate

**Remote Access:**
- 22/tcp: SSH
- 23/tcp: Telnet (ancient, unencrypted)
- 3389/tcp: RDP (Windows)
- 5900/tcp: VNC

**File Sharing:**
- 21/tcp: FTP (control), 20/tcp: FTP (data)
- 445/tcp: SMB (Windows shares)
- 139/tcp: NetBIOS/SMB (legacy)
- 2049/tcp: NFS (Unix/Linux shares)

**Databases:**
- 3306/tcp: MySQL
- 5432/tcp: PostgreSQL  
- 1433/tcp: MS SQL
- 27017/tcp: MongoDB
- 6379/tcp: Redis

**Email:**
- 25/tcp: SMTP
- 110/tcp: POP3
- 143/tcp: IMAP
- 587/tcp: SMTP (submission)

**DNS:** 53/tcp+udp

**Pro Tip:** First 1024 ports are "well-known". Above that is less standardized but patterns exist.`,
      practice: {
        question: "You find port 5432 open. What's the first enumeration step?",
        options: [
          "Try default creds postgres:postgres",
          "Run gobuster for web directories",
          "Check for anonymous SMB access",
          "Attempt SSH brute force"
        ],
        correct: 0,
        explanation: "5432 = PostgreSQL. Try default creds first (postgres:postgres, postgres:password). Then enumerate users/databases. This is exactly what you did on the HTB Cap box."
      }
    },
    {
      id: 4,
      title: "TCP vs UDP",
      category: "TCP/IP",
      content: `**TCP (Transmission Control Protocol):**
✓ Connection-oriented (handshake required)
✓ Reliable (guarantees delivery, retransmits lost packets)
✓ Ordered (packets arrive in sequence)
✓ Slower (overhead from acknowledgments)
✓ Flow control (prevents overwhelming receiver)

**UDP (User Datagram Protocol):**
✓ Connectionless (no handshake)
✓ Unreliable (no delivery guarantee)
✓ No ordering (packets may arrive out of order)
✓ Faster (no overhead)
✓ No flow control

**When Each Is Used:**
- TCP: HTTP, SSH, databases, anything needing reliability
- UDP: DNS, streaming, VoIP, games (speed > reliability)

**Scanning Difference:**
- TCP: Send SYN, get response = definitive
- UDP: Send packet, no response = probably filtered OR open
  (UDP scan is unreliable, takes forever)

**Pentesting Reality:**
Focus on TCP. UDP scanning is slow and noisy. Exception: DNS (53/udp), SNMP (161/udp), TFTP (69/udp).`,
      practice: {
        question: "Why does 'nmap -sU' take so long?",
        options: [
          "UDP ports respond slower than TCP",
          "No response usually means filtered OR open (ambiguous)",
          "UDP requires three-way handshake",
          "UDP uses more bandwidth"
        ],
        correct: 1,
        explanation: "UDP is connectionless. No response = probably filtered, but could be open and just not responding. Nmap has to wait for timeouts to determine state. That's why UDP scans take 20x longer than TCP."
      }
    },
    {
      id: 5,
      title: "DNS Deep Dive",
      category: "Services",
      content: `**DNS Basics:**
Translates domain names → IP addresses

**Record Types:**
- A: IPv4 address
- AAAA: IPv6 address  
- CNAME: Alias to another domain
- MX: Mail server
- NS: Nameserver
- TXT: Arbitrary text (SPF, DKIM, verification)
- PTR: Reverse lookup (IP → domain)

**DNS Query Process:**
1. Check local cache
2. Query recursive resolver (ISP/8.8.8.8)
3. Resolver queries root servers
4. Root points to TLD servers (.com)
5. TLD points to authoritative nameserver
6. Authoritative returns answer

**DNS for Pentesting:**
- Zone transfers (AXFR): Try to dump all records
- Subdomain enumeration: Find hidden services
- DNS tunneling: Exfiltrate data via DNS queries
- MX records reveal mail infrastructure
- TXT records sometimes leak info

**Key Commands:**
\`\`\`bash
dig example.com              # A record
dig example.com MX           # Mail servers
dig example.com ANY          # All records
dig @ns1.example.com AXFR    # Zone transfer attempt
host -l example.com ns1.example.com  # Zone transfer (alternative)
\`\`\``,
      practice: {
        question: "You run 'dig example.com ANY' and see multiple A records pointing to different IPs. What's this likely indicating?",
        options: [
          "Misconfigured DNS",
          "Load balancing/CDN",
          "DNS cache poisoning",
          "DNS tunneling attack"
        ],
        correct: 1,
        explanation: "Multiple A records = round-robin DNS or CDN. Each query returns IPs in different order for load distribution. Cloudflare, Akamai, etc. use this."
      }
    },
    {
      id: 6,
      title: "ARP & MAC Addresses",
      category: "Fundamentals",
      content: `**ARP (Address Resolution Protocol):**
Maps IP addresses (Layer 3) to MAC addresses (Layer 2)

**How It Works:**
1. Host needs to send to 192.168.1.100
2. Broadcasts: "Who has 192.168.1.100? Tell 192.168.1.50"
3. Target responds: "192.168.1.100 is at AA:BB:CC:DD:EE:FF"
4. Sender caches this in ARP table

**MAC Address Structure:**
- 48 bits (6 octets): AA:BB:CC:DD:EE:FF
- First 3 octets = OUI (manufacturer)
- Last 3 octets = unique device ID

**ARP Commands:**
\`\`\`bash
arp -a                 # View ARP cache
arp -d IP              # Delete entry
ip neigh               # Linux alternative
\`\`\`

**Why This Matters:**
- ARP only works on local network (same subnet)
- Cross-subnet = routing (Layer 3)
- ARP spoofing = MITM attacks on LAN

**ARP Spoofing Attack:**
1. Send fake ARP replies to victim
2. "192.168.1.1 (gateway) is at YOUR_MAC"
3. Victim sends traffic to you instead of gateway
4. You forward it (man-in-the-middle)

**Tools:** arpspoof, ettercap, bettercap`,
      practice: {
        question: "You're on 192.168.1.0/24 network. Target is 192.168.2.100. Will ARP resolve the target's MAC?",
        options: [
          "Yes, ARP broadcasts reach all networks",
          "No, different subnet - need Layer 3 routing",
          "Only if both are on same physical switch",
          "Yes, but need to enable IP forwarding"
        ],
        correct: 1,
        explanation: "Different subnets = different broadcast domains. ARP only works within same subnet. To reach 192.168.2.100, you'd ARP for your gateway, which routes the packet at Layer 3."
      }
    },
    {
      id: 7,
      title: "Routing & Gateways",
      category: "TCP/IP",
      content: `**Routing Table Basics:**
Determines where to send packets

**Check Your Routes:**
\`\`\`bash
route -n              # Linux
ip route              # Linux (modern)
netstat -rn           # Universal
\`\`\`

**Typical Output:**
\`\`\`
Destination    Gateway        Genmask         Iface
0.0.0.0        192.168.1.1    0.0.0.0         eth0    (default)
192.168.1.0    0.0.0.0        255.255.255.0   eth0    (local)
\`\`\`

**Routing Decision:**
1. Is destination on local subnet? → Send directly (ARP)
2. Not local? → Send to gateway (default route)

**Default Route (0.0.0.0/0):**
- "If no specific route matches, use this"
- Usually your router/gateway

**For Pentesting:**
- Pivoting requires adding routes to internal subnets
- SSH tunnels create new routes
- Understanding routes = understanding network topology

**Add Route Example:**
\`\`\`bash
# Access 10.10.11.0/24 via compromised host at 192.168.1.50
ip route add 10.10.11.0/24 via 192.168.1.50
\`\`\`

**Subnet Routing in Your Lab:**
You had to route HTB's 10.10.x.x subnet through your Parrot VM because Mac couldn't reach it directly.`,
      practice: {
        question: "Your routing table has no route for 10.10.11.0/24. Where does a packet to 10.10.11.50 go?",
        options: [
          "Dropped (no route)",
          "Default gateway (0.0.0.0/0 route)",
          "Broadcast to local network",
          "Queued until route added"
        ],
        correct: 1,
        explanation: "No specific route = use default gateway. That's the whole point of 0.0.0.0/0 - catch-all for everything not explicitly routed."
      }
    },
    {
      id: 8,
      title: "NAT & Port Forwarding",
      category: "Advanced",
      content: `**NAT (Network Address Translation):**
Translates private IPs ↔ public IPs

**Why NAT Exists:**
- IPv4 address exhaustion
- Only one public IP for entire home/office
- Private IPs (10.x, 172.16.x, 192.168.x) not routable on internet

**NAT Types:**

**1. SNAT (Source NAT):**
- Outbound traffic
- Private IP → Public IP
- Router rewrites source address

**2. DNAT (Destination NAT) / Port Forwarding:**
- Inbound traffic
- Public IP:Port → Private IP:Port
- Example: 203.0.113.5:80 → 192.168.1.100:80

**Port Forwarding Example:**
\`\`\`bash
# SSH tunnel (local port forward)
ssh -L 8080:localhost:80 user@server
# Access server's port 80 via your localhost:8080

# Reverse SSH tunnel
ssh -R 8080:localhost:22 user@server
# Server can access your SSH via its localhost:8080
\`\`\`

**Your HTB Setup:**
Parrot VM connects to HTB VPN. Your Mac can't directly reach HTB machines. Solution: NAT/routing through Parrot.

**iptables NAT:**
\`\`\`bash
# Enable forwarding
echo 1 > /proc/sys/net/ipv4/ip_forward

# SNAT outgoing traffic
iptables -t nat -A POSTROUTING -o tun0 -j MASQUERADE

# DNAT port forward
iptables -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to 10.10.11.50:80
\`\`\``,
      practice: {
        question: "You SSH to a compromised server with 'ssh -L 3306:db.internal:3306 user@compromised'. Now what?",
        options: [
          "Connect to compromised:3306 to reach database",
          "Connect to localhost:3306 to reach database",
          "Connect to db.internal:3306 directly",
          "Database is now exposed on internet"
        ],
        correct: 1,
        explanation: "-L creates LOCAL port forward. Your localhost:3306 → compromised → db.internal:3306. This is exactly how you accessed PostgreSQL on HTB machines from your Mac."
      }
    },
    {
      id: 9,
      title: "Firewalls & Filtering",
      category: "Security",
      content: `**Firewall Types:**

**1. Stateless (Packet Filter):**
- Examines each packet independently
- Rules based on: IP, port, protocol
- Fast but dumb

**2. Stateful:**
- Tracks connection state
- Allows return traffic for established connections
- Knows if packet is part of existing conversation

**3. Application Layer:**
- Deep packet inspection
- Understands protocols (HTTP, DNS, etc.)
- Can block based on content

**Default Policies:**
- **Whitelist** (deny all, allow specific): More secure
- **Blacklist** (allow all, deny specific): Less secure

**Common Firewall Behaviors:**
- **ACCEPT**: Allow packet through
- **DROP**: Silently discard (looks like filtered)
- **REJECT**: Send back RST/ICMP unreachable (reveals presence)

**Evasion Techniques:**
- Fragmentation: Split packets to avoid inspection
- Timing: Slow scans to avoid rate limits
- Source port: Use port 53/80 as source (often allowed)
- Decoys: Make scan look like it's from multiple IPs

**Nmap Firewall Evasion:**
\`\`\`bash
nmap -f target              # Fragment packets
nmap -D RND:10 target       # Use 10 random decoys
nmap --source-port 53       # Spoof source port
nmap -T2 target             # Slower timing (T0-T5)
\`\`\`

**Reality Check:**
Modern firewalls are good. Evasion often doesn't work. But worth trying on older infrastructure.`,
      practice: {
        question: "Nmap shows a port as 'filtered'. What does this mean?",
        options: [
          "Port is open but service crashed",
          "Port is closed by the service",
          "Firewall is blocking/dropping packets",
          "Service requires authentication"
        ],
        correct: 2,
        explanation: "'Filtered' = firewall dropping packets or ICMP unreachable received. Can't determine if port is actually open. Contrast with 'closed' (RST received) or 'open' (service responded)."
      }
    },
    {
      id: 10,
      title: "HTTP Deep Dive",
      category: "Services",
      content: `**HTTP Request Structure:**
\`\`\`
GET /api/users HTTP/1.1
Host: example.com
User-Agent: Mozilla/5.0
Accept: application/json
Cookie: session=abc123

[optional body]
\`\`\`

**HTTP Methods:**
- **GET**: Retrieve data (params in URL)
- **POST**: Submit data (params in body)
- **PUT**: Update/replace resource
- **DELETE**: Remove resource
- **OPTIONS**: Check allowed methods
- **HEAD**: Like GET but no body

**Response Codes:**
- **2xx**: Success (200 OK, 201 Created)
- **3xx**: Redirect (301 Moved, 302 Found)
- **4xx**: Client error (400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found)
- **5xx**: Server error (500 Internal Error, 503 Unavailable)

**Key Headers for Security:**
- **Authorization**: Bearer tokens, Basic auth
- **Cookie**: Session management
- **Content-Type**: What data format
- **User-Agent**: What browser/client
- **Referer**: Where request came from
- **X-Forwarded-For**: Original client IP (proxy)

**For Pentesting:**
- Manipulate headers (Host, User-Agent, X-Forwarded-For)
- Test different methods (PUT/DELETE on GET endpoints)
- Modify cookies/tokens
- Upload using POST/PUT

**Tools:**
- curl: Command-line HTTP
- Burp Suite: Intercept/modify requests
- gobuster: Directory/file enumeration`,
      practice: {
        question: "Server returns 403 Forbidden for /admin. What's the difference from 401 Unauthorized?",
        options: [
          "403 = authenticated but no permission, 401 = not authenticated",
          "403 = not authenticated, 401 = authenticated but denied",
          "No functional difference",
          "403 = permanent, 401 = temporary"
        ],
        correct: 0,
        explanation: "401 = you need to authenticate (login). 403 = you ARE authenticated but don't have permission. 403 reveals the endpoint exists but you can't access it."
      }
    },
    {
      id: 11,
      title: "SSL/TLS & HTTPS",
      category: "Security",
      content: `**SSL/TLS Overview:**
Encrypts traffic between client and server

**SSL vs TLS:**
- SSL: Outdated (SSL 2.0/3.0 broken)
- TLS: Modern (TLS 1.2/1.3 secure)
- Everyone still says "SSL" but means TLS

**How HTTPS Works:**
1. Client → Server: "Hello, let's use TLS"
2. Server → Client: Certificate + public key
3. Client verifies certificate (trusted CA?)
4. Client generates session key, encrypts with public key
5. Server decrypts with private key
6. Both use session key for symmetric encryption

**Certificate Chain:**
- Root CA (trusted by OS/browser)
- Intermediate CA
- Server certificate

**Common Ports:**
- 443/tcp: HTTPS
- 8443/tcp: HTTPS alternate

**Certificate Info:**
\`\`\`bash
openssl s_client -connect example.com:443
# Shows cert details, cipher used

nmap --script ssl-cert target
# Extracts certificate info
\`\`\`

**For Pentesting:**
- Self-signed certs = dev/internal systems (promising targets)
- Certificate CN/SAN = domain names (subdomain enum)
- Weak ciphers = downgrade attacks
- Certificate expiry/misconfiguration

**SSL Stripping:**
Attacker downgrades HTTPS → HTTP via MITM. Prevented by HSTS.`,
      practice: {
        question: "You see a self-signed certificate on 10.10.11.50:443. What does this suggest?",
        options: [
          "Production system with proper security",
          "Likely internal/dev system or cost-cutting",
          "Certificate was compromised",
          "Service is definitely vulnerable"
        ],
        correct: 1,
        explanation: "Self-signed = no trusted CA signature. Common on internal/dev systems or lazy deployments. Not inherently vulnerable but suggests less security focus. Production services typically use Let's Encrypt or commercial certs."
      }
    },
    {
      id: 12,
      title: "VPNs & Tunneling",
      category: "Advanced",
      content: `**VPN Types:**

**1. Site-to-Site:**
- Connects two networks
- Routers/firewalls handle VPN
- Users don't know it exists

**2. Remote Access:**
- Individual user → corporate network
- OpenVPN, WireGuard, IPSec
- What you use for HTB

**How VPNs Work:**
1. Encrypt traffic at source
2. Encapsulate in new packet
3. Send through internet
4. Decrypt at destination

**Split Tunnel vs Full Tunnel:**
- **Split**: Only traffic for VPN network goes through tunnel
- **Full**: All traffic goes through tunnel (more secure, slower)

**VPN Protocols:**
- **OpenVPN**: Most common, TCP or UDP
- **WireGuard**: Modern, faster, simpler
- **IPSec**: Enterprise standard, complex
- **PPTP**: Ancient, broken, don't use

**Your HTB Setup:**
\`\`\`bash
sudo openvpn lab_config.ovpn
# Creates tun0 interface
# Adds routes to 10.10.x.x networks
\`\`\`

**Check VPN:**
\`\`\`bash
ip addr show tun0          # VPN interface exists?
ip route | grep tun0       # Routes through VPN?
\`\`\`

**Tunneling Types:**
- **SSH Tunnels**: Port forwarding (what you've been using)
- **SOCKS Proxy**: Route all traffic through SSH
- **VPN**: Full network layer tunneling

**For Pentesting:**
- VPN = entry point to internal network
- Compromise VPN server = massive foothold
- Certificate-based VPN harder to crack than user/pass`,
      practice: {
        question: "Your HTB VPN drops. You reconnect but can't ping 10.10.11.50 (target). Most likely issue?",
        options: [
          "Target is offline",
          "Routes not re-added for 10.10.x.x subnet",
          "Firewall blocking ICMP",
          "DNS resolution failed"
        ],
        correct: 1,
        explanation: "VPN disconnect = routes removed. Reconnecting recreates tun0 but may not restore routes properly. Check 'ip route | grep tun0' and verify 10.10.0.0/16 routes through tun0."
      }
    },
    {
      id: 13,
      title: "Network Enumeration Strategy",
      category: "Methodology",
      content: `**Standard Recon Flow:**

**1. Host Discovery:**
\`\`\`bash
nmap -sn 10.10.11.0/24     # Ping scan
fping -ag 10.10.11.0/24    # Fast ping sweep
\`\`\`

**2. Port Scanning:**
\`\`\`bash
nmap -sS -p- 10.10.11.50            # All TCP ports
nmap -sU -top-ports 100 10.10.11.50  # Top 100 UDP
nmap -sV -p 22,80,445 10.10.11.50   # Service versions
\`\`\`

**3. Service Enumeration:**
Based on ports found:
- Port 80/443: gobuster, nikto, whatweb
- Port 445: enum4linux, smbclient
- Port 22: Banner grabbing, auth methods
- Port 21: Anonymous FTP check
- Databases: Default creds, version check

**4. Vulnerability Scanning:**
\`\`\`bash
nmap --script vuln 10.10.11.50
nmap --script discovery 10.10.11.50
\`\`\`

**5. Manual Exploration:**
- Browse websites, try common paths
- Check for misconfigurations
- Test default credentials
- Look for version-specific vulns

**Pro Tips:**
- Start broad (host discovery), narrow down (specific ports)
- Don't skip service enumeration - versions matter
- Save scan results: \`nmap -oA scan_name\`
- Parallel scans: multiple terminals, different targets
- Rerun scans after gaining access (internal view)

**Your HTB Pattern:**
1. Nmap initial scan
2. Gobuster on web ports
3. Service-specific enum (SMB, databases)
4. Exploit → foothold
5. Rescan from inside`,
      practice: {
        question: "You find port 80 open. What's the logical first step after confirming web server?",
        options: [
          "Run SQLi scanner immediately",
          "Start Burp and manually browse entire site",
          "Run gobuster for hidden directories/files",
          "Check for default credentials"
        ],
        correct: 2,
        explanation: "Gobuster first = discover attack surface. Find admin panels, backups, config files. Then browse manually and test functionality. Always enumerate before attacking."
      }
    },
    {
      id: 14,
      title: "Pivoting & Lateral Movement",
      category: "Advanced",
      content: `**Pivoting Concept:**
Using compromised host A to attack host B (unreachable from attacker)

**Scenario:**
\`\`\`
You (10.8.1.50) → [Internet] → Server (203.0.113.5)

                              Internal Network (192.168.1.0/24)

                              Database (192.168.1.100)
\`\`\`

**Pivoting Techniques:**

**1. SSH Port Forward (Local):**
\`\`\`bash
ssh -L 3306:192.168.1.100:3306 user@203.0.113.5
# Now: localhost:3306 → Database
\`\`\`

**2. SSH Dynamic Forward (SOCKS):**
\`\`\`bash
ssh -D 1080 user@203.0.113.5
# Configure tools to use SOCKS proxy localhost:1080
# Example: proxychains nmap -sT 192.168.1.0/24
\`\`\`

**3. SSH Remote Forward:**
\`\`\`bash
# On compromised server:
ssh -R 8080:192.168.1.100:80 attacker@your.vps
# Your VPS:8080 now reaches internal web server
\`\`\`

**4. Meterpreter Pivot:**
\`\`\`bash
# In Metasploit:
route add 192.168.1.0 255.255.255.0 SESSION_ID
# Now Metasploit modules can target 192.168.1.0/24
\`\`\`

**5. Chisel (HTTP Tunnel):**
\`\`\`bash
# Your machine:
./chisel server -p 8080 --reverse

# Compromised host:
./chisel client your.ip:8080 R:1080:socks
# Creates SOCKS proxy on your machine
\`\`\`

**Your Use Case:**
You've been doing this with HTB - Mac → Parrot VM → HTB machines. Classic pivot.

**Key Principle:**
Every compromised host is a potential pivot point to deeper networks.`,
      practice: {
        question: "You compromised web server (10.10.11.50). Nmap from it reveals 172.16.1.0/24 network. Why can't you scan this from your attack box?",
        options: [
          "Your attack box firewall blocking it",
          "172.16.1.0/24 is private, only reachable from internal network",
          "Need root privileges to scan",
          "Nmap not installed on attack box"
        ],
        correct: 1,
        explanation: "172.16.0.0/12 is private (RFC 1918). Not routable on internet. Only web server can reach it because it's on the internal network. You need to pivot through web server using SSH/SOCKS/tunnel."
      }
    },
    {
      id: 15,
      title: "PCAP Analysis Fundamentals",
      category: "Analysis",
      content: `**PCAP (Packet Capture):**
Binary file containing captured network packets

**Capture Traffic:**
\`\`\`bash
# Capture on interface:
tcpdump -i eth0 -w capture.pcap

# Capture with filter:
tcpdump -i eth0 'port 80' -w web.pcap

# Capture N packets:
tcpdump -i eth0 -c 1000 -w sample.pcap
\`\`\`

**Analysis with tcpdump:**
\`\`\`bash
tcpdump -r capture.pcap              # Read all
tcpdump -r capture.pcap 'port 22'    # Filter SSH
tcpdump -r capture.pcap -A           # ASCII payload
tcpdump -r capture.pcap -X           # Hex + ASCII
\`\`\`

**Wireshark Display Filters:**
\`\`\`
ip.addr == 10.10.11.50         # Specific IP (src or dst)
tcp.port == 80                 # HTTP traffic
http.request.method == "POST"  # HTTP POST requests
tcp.flags.syn == 1             # SYN packets
ftp-data                       # FTP file transfers
\`\`\`

**What to Look For:**
- Cleartext credentials (FTP, HTTP, Telnet)
- Unusual traffic patterns (data exfil?)
- Failed connections (recon attempts?)
- Unencrypted data (database queries, API keys)

**Your HTB Experience:**
Cap machine - PCAP had captured admin credentials in cleartext. Classic pentesting find.

**Follow TCP Stream:**
Wireshark: Right-click packet → Follow → TCP Stream
Reconstructs entire conversation. Great for HTTP/FTP/Telnet.

**Extract Files:**
Wireshark: File → Export Objects → HTTP/FTP
Carves files transferred over network.`,
      practice: {
        question: "PCAP shows many packets with TCP SYN flag, no ACK responses. What's happening?",
        options: [
          "Normal web browsing",
          "Port scan in progress",
          "Firewall blocking all traffic",
          "Network congestion"
        ],
        correct: 1,
        explanation: "Many SYNs with no response = port scanning (likely SYN scan). Attacker trying multiple ports, not waiting for responses. Classic nmap -sS signature in packet captures."
      }
    },
    {
      id: 16,
      title: "SMB/CIFS Deep Dive",
      category: "Services",
      content: `**SMB (Server Message Block):**
File sharing protocol used by Windows (and Samba on Linux)

**Ports:**
- 445/tcp: SMB over TCP (modern)
- 139/tcp: SMB over NetBIOS (legacy)

**SMB Versions:**
- SMBv1: Old, vulnerable (WannaCry exploited this)
- SMBv2/3: Modern, more secure

**Enumeration:**
\`\`\`bash
# List shares:
smbclient -L //10.10.11.50 -N           # Null session
smbclient -L //10.10.11.50 -U username

# Connect to share:
smbclient //10.10.11.50/share -U username

# Full enumeration:
enum4linux -a 10.10.11.50

# Nmap scripts:
nmap --script smb-enum-shares 10.10.11.50
nmap --script smb-enum-users 10.10.11.50
\`\`\`

**Common Shares:**
- C$: Hidden admin share (full C drive)
- ADMIN$: Windows/System32 directory
- IPC$: Named pipes (used for enumeration)
- SYSVOL: Group policy info (on DCs)
- NETLOGON: Logon scripts (on DCs)

**Anonymous Access:**
Many systems allow null sessions (no auth) for basic enum. Always try first.

**Authentication:**
- NTLMv1/v2: Challenge-response (can be relayed)
- Kerberos: Token-based (Active Directory)

**For Pentesting:**
- Check for anonymous access first
- Look for sensitive files in shares
- Writable shares = potential payload delivery
- Crack NTLM hashes if captured

**Red Flags:**
- Anonymous writable shares
- Credentials in share names
- Overly permissive access (Everyone:Full Control)`,
      practice: {
        question: "You connect to //server/BackupShare and find password_backup.txt. Access denied. Why?",
        options: [
          "File is encrypted",
          "Can list files but can't read (restrictive ACLs)",
          "SMB version incompatibility",
          "File is corrupted"
        ],
        correct: 1,
        explanation: "Share permissions ≠ file permissions. You might have list access on share but not read access on specific files. Windows ACLs can be very granular. Use 'get password_backup.txt' in smbclient to see actual permission error."
      }
    },
    {
      id: 17,
      title: "Database Port Security",
      category: "Services",
      content: `**Database Exposure Pattern:**

**Proper Setup:**
Database on private network, only app server can connect.

**Improper Setup (Common):**
Database exposed directly to internet or reachable from DMZ.

**Why Databases Shouldn't Be Public:**
- Direct attack surface
- Bypass application logic/security
- Often use weak/default credentials
- Data exfiltration without app knowledge

**Quick Connection Tests:**

**PostgreSQL:**
\`\`\`bash
psql -h 10.10.11.50 -U postgres -d postgres
# Common usernames: postgres, admin, root
# Common passwords: postgres, admin, password, [blank]
\`\`\`

**MySQL:**
\`\`\`bash
mysql -h 10.10.11.50 -u root -p
# Common users: root, admin, mysql
\`\`\`

**MongoDB:**
\`\`\`bash
mongo mongodb://10.10.11.50:27017
# Often no auth required (huge security fail)
\`\`\`

**Redis:**
\`\`\`bash
redis-cli -h 10.10.11.50
# Usually no auth, direct command execution possible
\`\`\`

**MS SQL:**
\`\`\`bash
sqsh -S 10.10.11.50 -U sa -P password
# 'sa' = system admin account
\`\`\`

**Your HTB Experience:**
Multiple boxes had databases with default/weak creds. This is common in real world too, especially internal networks and cloud misconfigurations.

**Defense:**
- Bind to localhost only (127.0.0.1)
- If must be networked, use firewall rules
- Strong authentication always
- Separate network segment for data tier`,
      practice: {
        question: "Database on 10.10.11.50:5432 refuses connection. Which is LEAST likely the reason?",
        options: [
          "Firewall blocking your IP",
          "Database configured to listen on 127.0.0.1 only",
          "Strong password preventing access",
          "Wrong PostgreSQL version on client"
        ],
        correct: 3,
        explanation: "Connection refused = can't even reach the port, not an auth issue. Strong password would allow connection but fail at login. Version mismatch causes protocol errors after connecting, not connection refusal."
      }
    },
    {
      id: 18,
      title: "Network Segmentation",
      category: "Security",
      content: `**Network Segmentation Concept:**
Divide network into smaller isolated segments

**Common Segments:**

**1. DMZ (Demilitarized Zone):**
- Public-facing services (web, mail)
- Internet ← → Firewall ← → DMZ ← → Firewall ← → Internal

**2. Internal Network:**
- Workstations, file servers
- Normal business operations

**3. Management Network:**
- Out-of-band network for admins
- IPMI, iLO, console access

**4. Data/Database Tier:**
- Databases, data warehouses
- Restricted to application servers only

**Why Segment:**
- Limit blast radius (compromise one ≠ compromise all)
- Compliance requirements (PCI, HIPAA)
- Different security policies per segment

**Typical Segmentation Fail:**
Flat network - all devices can talk to all devices. Single compromise = full access.

**VLANs (Virtual LANs):**
- Logical network separation on same physical switch
- VLAN 10 = Management
- VLAN 20 = Servers
- VLAN 30 = Workstations

**For Pentesting:**
- Identify what segment you're in
- Map trust relationships between segments
- Pivot through segments (lateral movement)
- Find misconfigured ACLs/firewall rules

**Signs of Poor Segmentation:**
- Workstations can directly access database servers
- Any host can SSH to any other host
- Web DMZ can reach internal file shares
- Single subnet for everything`,
      practice: {
        question: "You compromise a web server in DMZ (172.16.1.50). It can't reach internal network (10.10.0.0/16). This is?",
        options: [
          "Misconfiguration - should be able to reach",
          "Good security - DMZ isolated from internal",
          "Network failure",
          "VPN required between segments"
        ],
        correct: 1,
        explanation: "DMZ → Internal should be heavily restricted or blocked entirely. Good security. DMZ compromise shouldn't give internal access. You'd need to find specific allowed channels (like database connections if web app uses internal DB)."
      }
    },
    {
      id: 19,
      title: "SNMP Enumeration",
      category: "Services",
      content: `**SNMP (Simple Network Management Protocol):**
Used to monitor/manage network devices (routers, switches, printers)

**Ports:**
- 161/udp: SNMP queries
- 162/udp: SNMP traps (notifications)

**SNMP Versions:**
- v1: Original, cleartext community strings
- v2c: Same as v1 with minor improvements
- v3: Encrypted, authentication (secure)

**Community Strings:**
Like passwords but called "community strings"
- **public**: Default read-only
- **private**: Default read-write

**What SNMP Reveals:**
- System info (OS, version, uptime)
- Network interfaces (IPs, MACs)
- Running processes
- Installed software
- User accounts
- Sometimes passwords in cleartext

**Enumeration Tools:**
\`\`\`bash
# Basic query:
snmpwalk -v2c -c public 10.10.11.50

# Brute force community strings:
onesixtyone -c /usr/share/seclists/Discovery/SNMP/common-snmp-community-strings.txt 10.10.11.50

# Nmap:
nmap -sU -p 161 --script snmp-brute 10.10.11.50
\`\`\`

**MIBs (Management Information Base):**
Hierarchical database of info SNMP can query
- System: 1.3.6.1.2.1.1
- Interfaces: 1.3.6.1.2.1.2
- Processes: 1.3.6.1.2.1.25

**For Pentesting:**
- Always try "public" first
- Look for network topology (map internal network)
- User enumeration
- Running services/processes

**Defense:**
- Disable if not needed
- Use SNMPv3 with strong auth
- Restrict to management network only
- Non-default community strings`,
      practice: {
        question: "snmpwalk returns process list showing 'sshd -D -o PermitRootLogin=yes'. What's significant?",
        options: [
          "Nothing, standard SSH config",
          "SSH daemon allows root login - potential target",
          "SSH is disabled",
          "Server using old SSH version"
        ],
        correct: 1,
        explanation: "PermitRootLogin=yes means you can SSH directly as root (if you have creds). High-value target. Many systems disable this by default. SNMP just revealed a security misconfiguration and confirmed SSH is running."
      }
    },
    {
      id: 20,
      title: "Network Attack Patterns",
      category: "Methodology",
      content: `**Common Attack Chains:**

**Pattern 1: External → Internal**
1. Find exposed web app/service
2. Exploit → foothold on DMZ
3. Enumerate internal network from compromised host
4. Pivot to internal systems
5. Escalate privileges
6. Lateral movement

**Pattern 2: Default Credentials**
1. Find service (DB, admin panel, etc.)
2. Try default creds (admin:admin, root:root)
3. Access granted → immediate control
4. Extract data or establish persistence

**Pattern 3: Information Disclosure**
1. Find leak (SNMP, unprotected share, directory listing)
2. Extract credentials/config files
3. Use creds elsewhere (password reuse)
4. Gain access to higher-value systems

**Pattern 4: Misconfigured Service**
1. Service exposed (database, Redis, MongoDB)
2. No authentication or weak auth
3. Direct data access or RCE
4. Pivot from there

**Your HTB Journey Shows This:**
- Cap: PCAP leak → creds → SSH access → privesc
- Default database creds → data access → further enum

**Real World Frequency:**
1. Default/weak passwords (very common)
2. Misconfigurations (common)
3. Unpatched services (common)
4. 0-days (rare, targeted attacks)

**Mindset Shift:**
CTF: Find the flag
Real: Chain together multiple small wins

**Defense Priority:**
1. Patch known vulnerabilities
2. Strong authentication everywhere
3. Principle of least privilege
4. Network segmentation
5. Monitoring/detection`,
      practice: {
        question: "You find: weak web app → SQLi → DB creds → SSH reuse → internal network access. This demonstrates?",
        options: [
          "Single point of failure",
          "Attack chain/lateral movement",
          "Zero-day exploitation",
          "Social engineering"
        ],
        correct: 1,
        explanation: "Classic attack chain. Each step enables the next. Web app vuln → DB → credential reuse → internal pivot. Defense in depth means breaking any link stops the chain. This is how real breaches happen - chaining multiple weaknesses."
      }
    }
  ];

  const currentLessonData = lessons[currentLesson];
  const progress = (completedLessons.size / lessons.length) * 100;

  const handleComplete = () => {
    setCompletedLessons(new Set([...completedLessons, currentLesson]));
    setShowAnswer(false);
    setUserAnswer('');
  };

  const handleNext = () => {
    if (currentLesson < lessons.length - 1) {
      setCurrentLesson(currentLesson + 1);
      setShowAnswer(false);
      setUserAnswer('');
    }
  };

  const handlePrevious = () => {
    if (currentLesson > 0) {
      setCurrentLesson(currentLesson - 1);
      setShowAnswer(false);
      setUserAnswer('');
    }
  };

  const isAnswerCorrect = parseInt(userAnswer) === currentLessonData.practice.correct;
  const isLessonComplete = completedLessons.has(currentLesson);

  return (
    <div className="min-h-screen bg-gray-900 text-gray-100 p-4">
      <div className="max-w-4xl mx-auto">
        {/* Header */}
        <div className="mb-8">
          <div className="flex items-center gap-3 mb-4">
            <Book className="w-8 h-8 text-blue-400" />
            <h1 className="text-3xl font-bold">NetLearn</h1>
          </div>

          {/* Progress Bar */}
          <div className="bg-gray-800 rounded-full h-3 overflow-hidden">
            <div 
              className="bg-blue-500 h-full transition-all duration-300"
              style={{ width: `${progress}%` }}
            />
          </div>
          <div className="flex justify-between mt-2 text-sm text-gray-400">
            <span>{completedLessons.size} / {lessons.length} completed</span>
            <span>{Math.round(progress)}%</span>
          </div>
        </div>

        {/* Lesson Navigation */}
        <div className="grid grid-cols-5 gap-2 mb-6">
          {lessons.map((lesson, idx) => (
            <button
              key={lesson.id}
              onClick={() => {
                setCurrentLesson(idx);
                setShowAnswer(false);
                setUserAnswer('');
              }}
              className={`p-2 rounded text-xs font-medium transition-all ${
                idx === currentLesson
                  ? 'bg-blue-600 text-white'
                  : completedLessons.has(idx)
                  ? 'bg-green-900 text-green-100'
                  : 'bg-gray-800 text-gray-400 hover:bg-gray-700'
              }`}
            >
              {completedLessons.has(idx) ? (
                <CheckCircle className="w-4 h-4 mx-auto" />
              ) : (
                <Circle className="w-4 h-4 mx-auto" />
              )}
            </button>
          ))}
        </div>

        {/* Main Content */}
        <div className="bg-gray-800 rounded-lg p-6 mb-6">
          <div className="mb-4">
            <span className="text-xs font-semibold text-blue-400 uppercase tracking-wide">
              {currentLessonData.category}
            </span>
            <h2 className="text-2xl font-bold mt-1">{currentLessonData.title}</h2>
          </div>

          <div className="prose prose-invert max-w-none">
            <div className="whitespace-pre-wrap text-gray-300 leading-relaxed">
              {currentLessonData.content.split('**').map((part, idx) => 
                idx % 2 === 0 ? part : <strong key={idx} className="text-blue-300">{part}</strong>
              )}
            </div>
          </div>
        </div>

        {/* Practice Section */}
        <div className="bg-gray-800 rounded-lg p-6 mb-6">
          <h3 className="text-xl font-bold mb-4 text-yellow-400">Practice Question</h3>
          <p className="mb-4 text-gray-300">{currentLessonData.practice.question}</p>

          <div className="space-y-2 mb-4">
            {currentLessonData.practice.options.map((option, idx) => (
              <button
                key={idx}
                onClick={() => setUserAnswer(idx.toString())}
                className={`w-full text-left p-3 rounded transition-all ${
                  userAnswer === idx.toString()
                    ? 'bg-blue-600 text-white'
                    : 'bg-gray-700 text-gray-300 hover:bg-gray-600'
                }`}
              >
                {option}
              </button>
            ))}
          </div>

          <button
            onClick={() => setShowAnswer(true)}
            disabled={!userAnswer}
            className="bg-yellow-600 hover:bg-yellow-700 disabled:bg-gray-700 disabled:text-gray-500 text-white px-6 py-2 rounded font-medium transition-all"
          >
            Check Answer
          </button>

          {showAnswer && (
            <div className={`mt-4 p-4 rounded ${
              isAnswerCorrect ? 'bg-green-900/30 border border-green-700' : 'bg-red-900/30 border border-red-700'
            }`}>
              <p className={`font-bold mb-2 ${isAnswerCorrect ? 'text-green-400' : 'text-red-400'}`}>
                {isAnswerCorrect ? '✓ Correct!' : '✗ Not quite.'}
              </p>
              <p className="text-gray-300">{currentLessonData.practice.explanation}</p>

              {!isLessonComplete && (
                <button
                  onClick={handleComplete}
                  className="mt-4 bg-green-600 hover:bg-green-700 text-white px-4 py-2 rounded font-medium transition-all"
                >
                  Mark Complete
                </button>
              )}
            </div>
          )}
        </div>

        {/* Navigation Buttons */}
        <div className="flex justify-between">
          <button
            onClick={handlePrevious}
            disabled={currentLesson === 0}
            className="flex items-center gap-2 bg-gray-700 hover:bg-gray-600 disabled:bg-gray-800 disabled:text-gray-600 text-white px-4 py-2 rounded font-medium transition-all"
          >
            <ArrowLeft className="w-4 h-4" />
            Previous
          </button>

          {currentLesson === lessons.length - 1 && completedLessons.size === lessons.length ? (
            <div className="flex items-center gap-2 text-green-400 font-bold">
              <Award className="w-6 h-6" />
              Course Complete!
            </div>
          ) : (
            <button
              onClick={handleNext}
              disabled={currentLesson === lessons.length - 1}
              className="flex items-center gap-2 bg-blue-600 hover:bg-blue-700 disabled:bg-gray-800 disabled:text-gray-600 text-white px-4 py-2 rounded font-medium transition-all"
            >
              Next
              <ArrowRight className="w-4 h-4" />
            </button>
          )}
        </div>
      </div>
    </div>
  );
};

export default NetworkingLearner;