1.5.3 Protocols & Ports

Understand the services, conversations, and exposed entry points on a network

The OSI and TCP/IP models explain where communication happens. Protocols and ports make that idea practical: a protocol defines the rules of a conversation, and a port shows which service is listening for that conversation.

1. What are Protocols?

Definition: A protocol is a set of rules and standards that define how data is transmitted and received across a network.

Why Standardization Matters

  • Interoperability: Devices from different vendors can communicate
  • Reliability: Predictable behavior across all implementations
  • Security: Known standards can be analyzed and secured
  • Scalability: Networks can grow without compatibility issues

Protocol Stack Concept

Protocols work in layers - each layer handles specific tasks and passes data to the next:

+-----------------------------+
|  Application (HTTP, FTP)    | <- User sees this
+-----------------------------+
|  Transport (TCP, UDP)       | <- Ports, reliability
+-----------------------------+
|  Network (IP)               | <- Routing, addressing
+-----------------------------+
|  Data Link (Ethernet)       | <- Local delivery
+-----------------------------+
|  Physical (Cables, WiFi)    | <- Actual transmission
+-----------------------------+

Once you know the rules of communication, the next step is knowing where a service listens. That is where ports come in.

2. What are Ports?

A port is a logical endpoint for network communication. Think of IP as the building address and port as the apartment number.

Socket = IP Address + Port Number
Example: 192.168.1.100:443 = IP 192.168.1.100, Port 443 (HTTPS)

Port Number Ranges

RangeNameDescriptionExamples
0-1023Well-KnownReserved for common services, requires root/admin80 (HTTP), 443 (HTTPS), 22 (SSH)
1024-49151RegisteredRegistered with IANA for specific apps3306 (MySQL), 8080 (HTTP-Alt)
49152-65535Dynamic/PrivateEphemeral ports for client connectionsRandom client source ports
Total ports: 65,536 (0-65535), which is 2^16 possibilities per IP address.

A port tells you which service is involved. TCP and UDP explain how that service sends or receives data.

3. TCP vs UDP

AspectTCPUDP
ConnectionConnection-orientedConnectionless
ReliabilityGuaranteed delivery, orderingBest effort, no guarantees
SpeedSlower (overhead)Faster (minimal overhead)
Header Size20 bytes minimum8 bytes
Use CasesHTTP, FTP, SSH, EmailDNS, VoIP, Gaming, Streaming
Error CheckingFull error recoveryChecksum only
Flow ControlYes (windowing)No

TCP 3-Way Handshake

    Client                    Server
       |                         |
       |---- SYN (seq=100) ---->|  1. Client initiates
       |                         |
       |<--- SYN-ACK (seq=300) --|  2. Server acknowledges
       |    ack=101)             |
       |                         |
       |---- ACK (ack=301) ---->|  3. Connection established
       |                         |
       |<==== DATA TRANSFER ===>|

TCP 4-Way Termination

    Client                    Server
       |                         |
       |---- FIN -------------->|  1. Client wants to close
       |<--- ACK ---------------|  2. Server acknowledges
       |                         |
       |<--- FIN ---------------|  3. Server ready to close
       |---- ACK -------------->|  4. Connection closed

When to Use Which?

  • TCP: use it when delivery and order matter, such as web pages, file transfers, and email
  • UDP: use it when speed and low overhead matter, such as live streams, games, and many DNS queries

4. Protocol and Port Reference

Security note: High-risk ports are commonly targeted in attacks. If a service is not needed, disable it. If it is needed, restrict access and monitor it.
Protocol Port TCP/UDP Purpose Risk Security Notes
FTP20, 21TCPFile TransferHighCleartext credentials, use SFTP/FTPS
SSH22TCPSecure ShellMediumBrute-forceable, use keys + fail2ban
Telnet23TCPRemote AccessHighCleartext traffic, avoid using it
SMTP25TCPEmail SendingHighOpen relay abuse, spam source
DNS53UDP/TCPDomain ResolutionMediumPoisoning, amplification DDoS
DHCP67, 68UDPIP AssignmentMediumRogue DHCP, starvation attacks
TFTP69UDPSimple File TransferHighNo authentication by default
HTTP80TCPWeb TrafficHighCleartext, MITM risk, use HTTPS
Kerberos88TCP/UDPAuthenticationMediumPass-the-ticket, golden ticket
POP3110TCPEmail RetrievalHighCleartext, use POP3S
IMAP143TCPEmail RetrievalHighCleartext, use IMAPS
SNMP161, 162UDPNetwork ManagementHighDefault "public" community string
LDAP389TCP/UDPDirectory ServicesMediumLDAP injection attacks
HTTPS443TCPSecure WebLowVerify cert validity
SMB445TCPFile SharingHighEternalBlue, WannaCry, ransomware
SMTPS465TCPSecure EmailLowEncrypted SMTP
LDAPS636TCPSecure LDAPLowEncrypted directory access
IMAPS993TCPSecure IMAPLowEncrypted email retrieval
POP3S995TCPSecure POP3LowEncrypted email retrieval
MSSQL1433TCPSQL ServerHighSQLi, weak sa credentials
Oracle1521TCPOracle DBMediumTNS listener exploits
MySQL3306TCPMySQL DatabaseHighDefault credentials, SQLi, UDF exploits
RDP3389TCPRemote DesktopHighBlueKeep, brute force, NLA bypass
PostgreSQL5432TCPPostgreSQL DBMediumWeak trust authentication
VNC5900TCPRemote DesktopHighWeak or missing authentication
WinRM5985, 5986TCPWindows Remote MgmtMediumLateral movement pivot
Redis6379TCPCache/DatabaseHighOften has no authentication, RCE possible
HTTP Proxy8080TCPProxy ServerMediumMisconfigured open proxies

5. Commonly Exploited Ports

Critical Risk

21, 23, 25, 445, 3389

  • 21 (FTP): Anonymous access, cleartext
  • 23 (Telnet): No encryption ever
  • 25 (SMTP): Open relays, spam
  • 445 (SMB): EternalBlue, WannaCry
  • 3389 (RDP): BlueKeep CVE-2019-0708

High Risk

80, 110, 143, 161, 1433, 3306, 6379

  • 80 (HTTP): MITM, injection attacks
  • 110/143: Email credential theft
  • 161 (SNMP): Info disclosure
  • 1433/3306: Database attacks
  • 6379 (Redis): Unauthorized access

Medium Risk

22, 53, 88, 389, 5432

  • 22 (SSH): Brute force targets
  • 53 (DNS): Poisoning, tunneling
  • 88 (Kerberos): Ticket attacks
  • 389 (LDAP): Injection, enumeration
  • 5432 (Postgres): Trust auth bypass

Critical Port Examples

Port 445 (SMB)

Why it matters: SMB is deeply integrated into Windows file sharing and administration. A serious SMB issue can expose sensitive files or lead to full system compromise.

Famous Exploits:

  • EternalBlue (MS17-010) - WannaCry, NotPetya ransomware
  • SMBGhost (CVE-2020-0796) - SMBv3 compression bug

How to reduce risk: Disable SMBv1, block port 445 at the firewall, and disable SMB where it is not needed.

Port 3389 (RDP)

Why it matters: RDP provides direct GUI access to Windows machines and is frequently targeted by brute-force and credential-stuffing attacks.

Famous Exploits:

  • BlueKeep (CVE-2019-0708) - Pre-auth RCE, wormable
  • Credential stuffing and brute force attacks

How to reduce risk: Require VPN access, enable NLA, enforce account lockout, and avoid exposing RDP directly to the internet.

6. Default Open Ports

Windows Default Services

PortServiceRecommendation
135RPC Endpoint MapperBlock externally
139NetBIOS SessionDisable if not needed
445SMBBlock externally, disable SMBv1
3389RDPVPN only, or disable

Linux Default Services

PortServiceRecommendation
22SSHKey auth only, fail2ban
111RPCbindBlock if not using NFS
Check & Close Unnecessary Ports
# Windows - Check listening ports netstat -ano | findstr LISTENING Get-NetTCPConnection -State Listen # Linux - Check listening ports ss -tuln netstat -tulpn # Windows - Disable a service sc config "service_name" start= disabled # Linux - Stop and disable a service sudo systemctl stop service_name sudo systemctl disable service_name

7. Port Scanning Commands

Nmap Port Scans
# TCP connect scan, all 65535 ports nmap -sT -p- 192.168.1.1 # UDP scan (slower, root required) nmap -sU -p 53,161,500 192.168.1.1 # Version detection on common ports nmap -sV -p 22,80,443,3306 target.com # Aggressive scan (OS, version, scripts, traceroute) nmap -A target.com # Stealth SYN scan (half-open, faster) sudo nmap -sS -p 1-1000 192.168.1.0/24 # Script scan for vulnerabilities nmap --script vuln target.com
Check Local Listening Ports
# Windows netstat -ano | findstr LISTENING netstat -ano | findstr :445 # Check specific port # Linux ss -tuln netstat -tulpn lsof -i :445 # What's using port 445

8. Protocol Deep Dives

8.1 DNS (Port 53)

How it works: Translates human-readable domain names to IP addresses.

Resolution Types

  • Recursive: DNS server does all the work, returns final answer
  • Iterative: DNS server returns referrals, client follows chain

Record Types

TypePurposeExample
AIPv4 addressgoogle.com -> 142.250.190.46
AAAAIPv6 addressgoogle.com -> 2607:f8b0:4004:...
MXMail serverPriority + mail server hostname
CNAMEAliaswww.example.com -> example.com
TXTText dataSPF, DKIM, domain verification
NSName serversAuthoritative DNS servers
PTRReverse lookupIP -> domain name

DNS Attacks

  • DNS Poisoning: Inject fake records into cache
  • DNS Amplification: DDoS using open resolvers
  • DNS Tunneling: Exfiltrate data over DNS queries
DNS Commands
# Windows/Linux nslookup google.com nslookup -type=MX google.com # Linux dig (more powerful) dig google.com ANY dig +short google.com dig @8.8.8.8 google.com # Use specific DNS server # Reverse lookup host 142.250.190.46

8.2 DHCP (Ports 67, 68)

Purpose: Automatically assigns IP addresses to devices on a network.

DORA Process

Client                           Server
   |                                |
   |--- Discover (broadcast) ----->|  "Who can give me an IP?"
   |                                |
   |<------ Offer -----------------|  "I can offer 192.168.1.50"
   |                                |
   |--- Request ------------------>|  "I'll take that IP"
   |                                |
   |<------ Acknowledge -----------|  "Here's your lease info"

DHCP Attacks

  • DHCP Starvation: Exhaust all available IPs
  • Rogue DHCP: Attacker's server gives malicious settings (gateway, DNS)

Defense: DHCP snooping, port security

8.3 ARP (Layer 2)

Purpose: Maps IP addresses to MAC addresses on local network.

ARP Spoofing/Poisoning

An attacker sends fake ARP replies claiming to be the gateway. If the attack works, traffic routes through the attacker as a man-in-the-middle.

Defense: Static ARP entries, Dynamic ARP Inspection (DAI)

ARP Commands
# View ARP table arp -a # Clear ARP cache (Windows) arp -d * # Linux - show ARP ip neighbor show

8.4 ICMP (Layer 3)

Purpose: Error reporting and diagnostics (ping, traceroute).

ICMP Types

TypeNameUse
0Echo ReplyPing response
3Destination UnreachableHost/port unreachable
5RedirectRoute redirection, which can be abused
8Echo RequestPing
11Time ExceededTTL expired (traceroute)

ICMP Attacks

  • Ping of Death: Oversized ICMP packet crashes system (historical)
  • ICMP Tunneling: Hide data in ping packets to bypass firewalls
  • Smurf Attack: Broadcast ping flood (historical)

9. Security Corner

Port Scanning Ethics & Legality

Legal warning:
  • Do not scan systems you do not own or have written permission to test
  • Port scanning can be illegal in many jurisdictions
  • Always get explicit authorization in writing before testing
  • Use isolated lab environments for learning

Firewall Rules Based on Ports

Windows Firewall Examples
# Block incoming port 23 (Telnet) netsh advfirewall firewall add rule name="Block Telnet" dir=in action=block protocol=tcp localport=23 # Allow only specific IP to access RDP netsh advfirewall firewall add rule name="RDP Trusted" dir=in action=allow protocol=tcp localport=3389 remoteip=10.0.0.5
Linux iptables Examples
# Block incoming Telnet iptables -A INPUT -p tcp --dport 23 -j DROP # Allow SSH only from specific subnet iptables -A INPUT -p tcp -s 192.168.1.0/24 --dport 22 -j ACCEPT iptables -A INPUT -p tcp --dport 22 -j DROP

Principle of Least Privilege for Ports

  • Only open ports that are needed: every open port is an attack surface
  • Default deny: block all, then allow specific ports
  • Regular auditing: check for unexpected listening services
  • Network segmentation: keep sensitive services on isolated networks

10. Pentesting Relevance

Port Scanning Methodology

  1. Discovery: Find live hosts (ping sweep)
  2. Port Scan: Identify open ports
  3. Service Detection: What's running on each port
  4. Version Detection: Specific software versions
  5. Vulnerability Scan: Known CVEs for those versions

Banner Grabbing

Retrieve service information to identify software and versions:

Banner Grabbing Techniques
# Netcat manual banner grab nc -nv 192.168.1.1 22 nc -nv 192.168.1.1 80 # Nmap banner script nmap -sV --script=banner 192.168.1.1 # Telnet to web server (HTTP) telnet target.com 80 GET / HTTP/1.0 [press Enter twice] # cURL for HTTP headers curl -I http://target.com
Practice note: Banner information often reveals exact software versions, which helps you research relevant CVEs for an authorized lab or assessment.

11. Knowledge Check Quiz

Q1: What port does HTTPS use?
Q2: Which protocol is connectionless?
Q3: SMB runs on which port and is vulnerable to which famous exploit?
Q4: What is the correct order of TCP 3-way handshake?
Q5: Which port range is considered "well-known" ports?
Q6: Why is Telnet (port 23) considered high risk?
Q7: DNS primarily uses which transport protocol?
Q8: What does DORA stand for in DHCP?
Q9: Which Nmap flag performs a version detection scan?
Q10: Redis (port 6379) is high risk because:
Q11: What command shows listening ports on Linux?
Q12: ARP spoofing enables what type of attack?
Q13: Which port is used for RDP?
Q14: TCP header size is __ bytes minimum, UDP is __ bytes:
Q15: What is a socket?
Q1: 443
Q2: UDP
Q3: Port 445, EternalBlue
Q4: SYN -> SYN-ACK -> ACK
Q5: 0-1023
Q6: It transmits everything in cleartext
Q7: UDP primarily (TCP for large transfers)
Q8: Discover, Offer, Request, Acknowledge
Q9: -sV
Q10: It often has no authentication enabled
Q11: ss -tuln
Q12: Man-in-the-Middle
Q13: 3389
Q14: 20, 8
Q15: IP address + Port number combination