Skip to content
Tutorials Center
My learning

Topics

Lesson 62 of 79 ยท Network Security

Network Security Fundamentals

Learn the basics of network security: the CIA triad, sniffing, spoofing, man-in-the-middle and DoS attacks, attack surface, defense in depth and threat modeling.

The Internet was designed to move packets between researchers who trusted one another. Nothing in the original IP, TCP, DNS or SMTP protocols asks "who are you?" or "has this been changed on the way?". Today the same network carries banking, medical records and private conversations, so security has to be added on top, layer by layer.

This lesson gives you the vocabulary and the mental model for the rest of the security chapter: what we are protecting (the CIA triad), who attacks and how (sniffing, spoofing, man-in-the-middle, denial of service), why systems have an "attack surface", how defense in depth stacks protections, and how to think systematically with a threat model. The techniques that stop the attacks come next in cryptography for networking and TLS and HTTPS.

The goals: the CIA triad

Almost every security requirement falls into one of three goals.

  • Confidentiality: only the intended people can read the data. A stranger on the same Wi-Fi must not read your messages. The main tool is encryption.
  • Integrity: data is not changed, by accident or on purpose, without anyone noticing. A bank transfer must still say 100 when it arrives, not 10,000. Tools: hashes, message authentication codes and digital signatures.
  • Availability: the service works when you need it. An attack that makes a site unreachable breaks no secrets and changes no data, but it is still a security failure. Tools: redundancy, capacity, rate limiting and good operations.

The triad is often extended with a few related ideas:

  • Authentication: proving who you (or a server) are. A password, a certificate, a key.
  • Authorization: deciding what an authenticated party may do.
  • Non-repudiation: the sender cannot later deny having sent a message, normally through a digital signature.
  • Accountability: actions can be traced to an identity through logs.

The three goals can pull against each other. A system with no network connection is perfectly confidential and useless. Most design is about choosing the right balance for the thing you protect.

Who is the attacker, and where?

The network is a shared, mostly untrusted medium. An attacker may be in one of several positions:

  • On the same local network: on your coffee shop Wi-Fi, or in the same office VLAN. They can see broadcast traffic and try attacks like ARP spoofing.
  • On the path: an ISP, a compromised router, or an attacker who has diverted routes with a BGP hijack. They can see and modify anything that is not protected end to end.
  • Anywhere on the Internet: a remote attacker who can send packets to your public services but sees none of your traffic.
  • Inside: a malicious or compromised insider or device, which firewalls at the edge do not help against.

The standard way to model the capabilities of an attacker is to ask two questions. Can they only observe (a passive attacker), or can they also inject, drop and modify packets (an active attacker)? Cryptographic protocols are usually designed against an active attacker who controls the whole network between the two endpoints.

Core threats

Sniffing (eavesdropping)

On a shared medium, every device can see frames that were not meant for it. Wi-Fi is broadcast by nature, old hubs repeated every frame to every port, and a router or a tap anywhere on the path sees all packets passing through. A packet sniffer records them (you will use the legitimate versions in packet capture with tcpdump and Wireshark). Anything sent in plaintext, such as FTP, Telnet, HTTP and old email logins, is exposed, including passwords and cookies. Sniffing is a passive attack: it leaves no trace. The defense is encryption in transit.

Spoofing

Spoofing means forging an identity field. Source IP addresses are not authenticated, so an attacker can send packets claiming to come from anyone. The same goes for MAC addresses (MAC spoofing), the sender of an email, DNS responses and ARP replies. Spoofing alone is mostly used to hide the origin of an attack, to bypass filters that trust an address, or as the first step of something bigger. Defenses: authenticate with cryptography instead of trusting addresses, filter forged source addresses at the network edge (ingress filtering, BCP 38), and validate responses (for example DNSSEC and TLS).

Man-in-the-middle (MITM)

In a man-in-the-middle attack, the attacker sits between two parties, relays their traffic, and can read or change it while each side believes it talks to the other. It can be done by spoofing ARP or DNS, running a fake Wi-Fi access point ("evil twin"), or simply by controlling a router. Encryption alone does not stop it: if you set up an encrypted channel with the attacker instead of the real server, the attacker decrypts and re-encrypts everything. The real defense is authentication of the other end, which is what certificates in TLS provide.

flowchart LR
    U["Alice"] -->|"thinks she talks to the bank"| M["Attacker<br/>(reads and edits)"]
    M -->|"relays, modified"| B["Bank"]
    B --> M
    M --> U

Both sides see a working connection. The attacker sits in the middle and can read and change messages unless the endpoints authenticate each other.

Replay and tampering

Even without reading anything, an attacker can replay a captured valid message (for example "transfer 100") or tamper with unprotected fields. Integrity protection plus freshness (a nonce, a sequence number or a timestamp) defeats both. The demonstration below shows tampering in action.

Python Tampering: without and with an integrity check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Denial of service (DoS and DDoS)

A denial-of-service attack targets availability. The attacker overwhelms a resource: bandwidth (flood the link), a protocol state table (a SYN flood fills the half-open connection table; see TCP segments and the handshake), or application work (requests that make the server do expensive operations). When thousands of compromised machines, a botnet, send the traffic, it is a distributed denial of service (DDoS), which is hard to block because it comes from everywhere. Some DDoS attacks use amplification: the attacker sends a small request with a spoofed source address to a server that answers with a much larger response, aimed at the victim. DNS and some UDP services have been abused this way. The defenses are covered in common attacks and how to defend.

Other common threats

  • Malware (viruses, worms, ransomware, botnet agents) arrives by email, downloads or exploits and spreads across the network.
  • Phishing and social engineering trick people instead of machines. No firewall stops a user who types a password into a fake page.
  • Password attacks: guessing, credential stuffing with leaked passwords, and brute force.
  • Scanning and exploitation: finding open ports and unpatched software.
  • Rogue devices: an unknown access point or DHCP server on the network.

Attack surface

The attack surface is the sum of all the ways an attacker can reach your system: every open port, every exposed service, every web form, every API endpoint, every user account, every employee who can be phished and every third-party dependency. A server with 20 open ports has a larger attack surface than one with a single port. Each exposed thing is something that might have a bug.

The first rule is therefore to reduce it:

  • Close or firewall every port that does not need to be public. Put management interfaces such as SSH and databases behind a VPN or an allow-list.
  • Remove software and features you do not use.
  • Patch known vulnerabilities promptly.
  • Apply least privilege: every account, program and service gets only the access it needs.
  • Keep secrets out of code and give each system its own credentials.

Defense in depth

No single protection is perfect. Defense in depth puts several independent layers in the way, so an attacker who defeats one still faces the next. A typical web service might combine:

  1. Perimeter: firewall and DDoS protection at the edge.
  2. Network: segmentation into zones (VLANs, subnets) so a compromised web server cannot talk freely to the database.
  3. Host: patching, minimal services, host firewalls and anti-malware.
  4. Application: input validation, authentication, authorization and secure coding.
  5. Data: encryption at rest and in transit, backups.
  6. People and process: training, monitoring, logging and an incident-response plan.
flowchart LR
    I["Internet"] --> F["Firewall<br/>and DDoS filter"] --> W["Web tier<br/>(DMZ)"] --> A["App tier"] --> D[("Database<br/>zone")]

Each arrow crosses a boundary with its own rules, so one breach does not give access to everything.

The idea is statistical too: if independent layers each stop a given attack with some probability, the chance of an attacker getting through all of them falls quickly. The simulation below makes that concrete, and also shows why layers must be independent.

Python How layers multiply protection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Threat modeling

You cannot defend against threats you have not thought about. Threat modeling is a structured way to find them before attackers do. A simple process:

  1. What are we protecting? List the assets: customer data, credentials, uptime.
  2. What does the system look like? Draw the components, the data flows and the trust boundaries (where data crosses from a less trusted zone into a more trusted one, such as the Internet to your web server).
  3. What can go wrong? Walk each flow and boundary with a checklist. STRIDE is a popular one: Spoofing, Tampering, Repudiation, Information disclosure, Denial of service, Elevation of privilege. Each letter pairs with a security property: authentication, integrity, non-repudiation, confidentiality, availability and authorization.
  4. How bad and how likely? Rate each threat by impact and likelihood, so you spend effort where the risk is highest. Risk is roughly likelihood times impact.
  5. What do we do? Mitigate (add a control), accept, transfer (insurance) or avoid (remove the feature).
  6. Did it work? Test, review and repeat when the system changes.

Think like an attacker about the cheapest path, not the cleverest one. Attackers rarely break strong encryption. They steal a password, use an unpatched service or trick a person.

Python A tiny STRIDE risk register

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Authentication methods and MFA

Authentication answers "who are you?" before authorization answers "what may you do?". Methods are grouped into factors:

Factor Examples Weakness
Something you know Password, PIN, security question Guessed, reused, phished, leaked
Something you have Phone, hardware key, smart card, one-time-code app Lost, stolen, cloned
Something you are Fingerprint, face, iris Cannot be changed if leaked; false accepts and rejects
Somewhere you are (weak signal) Corporate network, geolocation Spoofable (VPNs, location faking)

Single-factor authentication (SFA) uses one of these, almost always a password. Two-factor authentication (2FA) uses two different factors, such as a password and a code from a phone. Multi-factor authentication (MFA) is the general term for two or more. Two passwords are not two factors; they are the same factor twice.

Passwords, done properly

A server should never store passwords. It stores a salted, deliberately slow hash (Argon2, bcrypt, scrypt or PBKDF2): the salt is random per user, so identical passwords give different hashes, and the slowness makes guessing expensive after a database leak. Over the network, passwords must only travel inside TLS. Defenses at the login form include rate limiting, lockouts or delays, and checking passwords against lists of known-breached ones.

One-time codes and tokens

The usual "authenticator app" implements TOTP (time-based one-time password, RFC 6238). The server and the phone share a secret once, at enrolment (the QR code). After that, both compute HMAC(secret, current_time / 30 s) and show the last few digits, so the code changes every 30 seconds and no secret crosses the network at login time. HOTP (RFC 4226) is the older variant based on a counter. SMS codes are weaker, because phone numbers can be hijacked by SIM swapping and messages can be intercepted.

The example computes real TOTP codes with the standard library.

Python Compute a TOTP code

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The first line reproduces the official RFC 6238 test value, so you know the implementation is correct. The server accepts the current time step and its neighbors because phone and server clocks drift; a code from five minutes ago is rejected.

Passkeys and security keys

Codes can still be phished: a fake site asks for the password and the six digits, and relays both in real time. FIDO2 / WebAuthn security keys and passkeys are phishing-resistant. The device holds a private key for each site and signs a challenge that includes the site's real origin, so a look-alike domain gets nothing usable. Nothing secret is shared, and there is nothing to type.

Kerberos: single sign-on inside an organization

Kerberos (default port 88, the heart of Windows Active Directory) lets a user log in once and then use many services without sending the password again. A trusted server called the KDC has two parts. The authentication service (AS) checks you at login and gives you a ticket-granting ticket (TGT). The ticket-granting service (TGS) then trades the TGT for a service ticket for a particular server, which you present to that server.

sequenceDiagram
    participant U as User
    participant AS as KDC: AS
    participant TGS as KDC: TGS
    participant S as File server
    U->>AS: 1. I am alice
    AS-->>U: 2. TGT + session key (encrypted with alice's password key)
    U->>TGS: 3. TGT + request for the file server
    TGS-->>U: 4. Service ticket for the file server
    U->>S: 5. Service ticket + fresh authenticator
    S-->>U: 6. Access granted

The password never crosses the network after step 1, and tickets expire, so a stolen one stops working.

Kerberos relies on synchronized clocks (tickets and authenticators carry timestamps; a skew of more than a few minutes is rejected) and on the KDC being a single trusted target that must be protected. Compare its tickets with the certificates used in public-key authentication.

Choosing methods. Use a password manager and unique passwords, add phishing-resistant MFA to important accounts, and treat SMS as the fallback rather than the goal. Layering factors is defense in depth applied to login.

Authentication versus authorization

These two words are often mixed up. Authentication answers "who are you?" and authorization answers "what are you allowed to do?". Authorization always comes after authentication: the system first identifies you (password, key, biometric) and then checks a policy. Authentication is checked once per session or per request and proves identity; authorization is decided per resource and action, such as reading a file or changing a router setting.

Authentication uses factors of three kinds: something you know (password, PIN), something you have (phone, hardware key) and something you are (a biometric). Biometric authentication compares a measured trait, such as a fingerprint, face, iris or voice, with a stored template. It is convenient and hard to forget, but it is never an exact match, so it has two error rates: false accepts (letting the wrong person in) and false rejects (locking out the right one). A biometric cannot be changed if it leaks, so it is best used as one factor of several (see Authentication methods and MFA).

Common authorization models:

  • Role-based access control (RBAC): permissions belong to roles such as "operator" or "auditor", and users get roles. Easy to administer and to audit.
  • Attribute-based access control (ABAC): a rule looks at attributes of the user, the resource and the context (department, device health, time of day, location). Very flexible, but the rules get complex.
  • Resource-based and policy-based authorization: permissions are attached to the resource itself (an access control list on a file) or are written as central policies that a policy engine evaluates for every request.
Python RBAC and ABAC in a few lines

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Classic security models

Before networks were everywhere, researchers formalized how to keep information safe in a system with many users. Three models are still taught because they show different priorities.

Bell-LaPadula (confidentiality). Every subject has a clearance and every object a classification (for example public, secret, top secret). The rules are "no read up" (a subject cannot read an object above its clearance) and "no write down" (it cannot write to a lower level, which would leak secrets). It was designed for the military and protects confidentiality only.

Biba (integrity). It is Bell-LaPadula turned upside down: "no read down" and "no write up". A high-integrity process must not read untrusted data or let low-integrity processes write over trusted data, so bad data cannot contaminate good data.

Clark-Wilson (integrity for business). Instead of levels, it forces users to change important data only through approved programs. Its parts are constrained data items (CDIs, the protected data), unconstrained data items (UDIs, raw input that is not yet trusted), integrity verification procedures (IVPs, which check that the data is consistent) and transformation procedures (TPs, the only programs allowed to change a CDI, turning input into valid data). Access is granted to user, program, data triples, and duties are separated, so for example the person who enters a payment cannot also approve it. This is close to how real accounting and banking systems work.

Python Bell-LaPadula and Biba in one small checker

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The two tables are mirror images: what Bell-LaPadula forbids to protect secrets, Biba allows, and the other way around. A real system must decide whether confidentiality or integrity is more important for each kind of data.

Sandboxing

A sandbox runs a program in a restricted environment that limits the files, memory, devices and network it can touch. If the program is malicious or has a bug, the damage stays inside the box. Browsers sandbox each tab, mobile apps run in per-app sandboxes, and containers and virtual machines isolate server workloads. Security teams also detonate suspicious files in a sandbox to watch what they do before they reach a user. A sandbox lowers risk and keeps systems stable, but it is not perfect: attackers look for "sandbox escapes", and some malware detects the sandbox and behaves well until it is out.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A bank transfer arrives as amount=9000 although the sender typed 100. Which property was violated?

    Integrity means data is not altered without detection. Confidentiality concerns who can read the data, and availability concerns whether the service works.
  2. 2. Why is encryption alone not enough to stop a man-in-the-middle attack?

    If you negotiate keys with the attacker instead of the real server, the attacker decrypts and re-encrypts everything. Certificates and signatures authenticate the endpoint.
  3. 3. Which is an example of reducing the attack surface?

    Every exposed port, service or feature is something that can contain a bug. Removing what you do not need leaves less for an attacker to reach.
  4. 4. What does defense in depth rely on?

    No control is perfect, so independent layers (network, host, application, data, people) make a complete breach much less likely.
  5. 5. In STRIDE, which letter stands for the threat of making a service unavailable?

    D is Denial of service. S is Spoofing, T is Tampering, R is Repudiation, I is Information disclosure and E is Elevation of privilege.

Summary

  • Security aims at confidentiality, integrity and availability, supported by authentication, authorization, non-repudiation and accountability.
  • Typical network threats: sniffing, spoofing, man-in-the-middle, replay and tampering, and denial of service (including DDoS and amplification), plus malware, phishing and password attacks.
  • Plan against an active attacker who controls the network between the endpoints. Encryption needs authentication to stop man-in-the-middle attacks.
  • Shrink the attack surface, apply least privilege, and use defense in depth with independent layers.
  • Threat modeling (assets, data flows, trust boundaries, STRIDE, risk ranking, mitigation) turns vague worry into a ranked to-do list.
  • Authentication proves identity with something you know, have or are; multi-factor authentication combines different kinds, TOTP and passkeys are common second factors, and Kerberos lets users prove identity to many services without sending a password across the network.

Next, the building blocks that make the defenses work: cryptography for networking.