SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 3

Cybersecurity Fundamentals · Lesson 3 of 90 · 13 min

Core security design principles

least privilegeneed to knowdefence in depthseparation of dutiesfail secure vs fail safesecure by defaultsecure by designeconomy of mechanismcomplete mediationopen designKerckhoffs's principlesecurity through obscuritypsychological acceptabilityminimise attack surface

These are the notes for Cybersecurity Fundamentals (defensive), episode 3. Last time we learned what "secure" means (confidentiality, integrity, availability and more). Today: how do you build a system that's secure from the start, instead of patching holes forever? We invent the design principles engineers have used for fifty years, each by breaking a small Python program and fixing it: least privilege and need to know, separation of duties, defence in depth, fail secure vs fail safe, secure by default and secure by design, complete mediation, open design, Kerckhoffs's principle vs security through obscurity, economy of mechanism, psychological acceptability, minimising the attack surface, and finally the 1975 list by Saltzer and Schroeder. Every word is explained the first time it appears, and the Glossary at the end defines them all again. Every code sample runs as-is; outputs are real (Python 3).

The problems you'll solve

Problem Principle it teaches
An intern's script deletes every file Least privilege, need to know
One clerk makes and approves a fake payment Separation of duties (maker-checker)
A stolen password empties an account Defence in depth
The permission server is down and the door opens Fail secure (fail closed) vs fail safe
A router ships with password admin Secure by default, secure by design
Ravi left, but his old "yes" still opens files Complete mediation
"Nobody knows our secret method" Open design, Kerckhoffs's principle, security through obscurity
Rules people work around; a messy wiring closet Psychological acceptability, economy of mechanism, minimise attack surface

Problem 1: least privilege and need to know

A small office says "just give everyone full access". An intern runs a cleanup script in the wrong folder, and every file is gone. The mistake was small; the access made it a disaster.

A privilege is a permission to do something: read, write, delete, install, approve.

Demo 1: everyone gets everything

files = {"report.pdf", "salary.xlsx", "logo.png"}

PERMS = {"owner":  {"read", "delete"},
         "intern": {"read", "delete"}}  # "give all to all"

def delete_all(user):
    for f in sorted(files):
        if "delete" in PERMS[user]:
            files.discard(f)
            print(f"{user} deleted {f}")
        else:
            print(f"{user} denied: {f}")

delete_all("intern")     # cleanup script, wrong folder
print("left:", files)

Output:

intern deleted logo.png
intern deleted report.pdf
intern deleted salary.xlsx
left: set()

set() is Python's empty set: nothing left.

Demo 1b: only what the job needs

files = {"report.pdf", "salary.xlsx", "logo.png"}

PERMS = {"owner":  {"read", "delete"},
         "intern": {"read"}}            # only what is needed

def delete_all(user):
    for f in sorted(files):
        if "delete" in PERMS[user]:
            files.discard(f)
            print(f"{user} deleted {f}")
        else:
            print(f"{user} denied: {f}")

delete_all("intern")     # cleanup script, wrong folder
print("left:", sorted(files))

Output:

intern denied: logo.png
intern denied: report.pdf
intern denied: salary.xlsx
left: ['logo.png', 'report.pdf', 'salary.xlsx']

Same script, same mistake, no damage.

  • Least privilege: every user and every program gets only the minimum privileges its job needs, for only as long as it needs them.
  • Need to know: you see information only if your work needs it. A hotel cook enters the kitchen, not the cash room.

Least privilege limits the blast radius (how much damage one failure can do) of honest mistakes and of attackers: a thief who steals the intern's account gets an account that can only read.

Problem 2: separation of duties

A bank locker has two keyholes: your key alone can't open it, and neither can the bank's master key. Separation of duties splits a risky task so no single person can complete it alone. In offices it's the maker-checker rule: one person makes a request, a different person checks and approves it. (Saltzer and Schroeder called the general idea separation of privilege: "require two keys".)

Demo 2: maker and checker must differ

def pay(amount, to, made_by, approved_by):
    if made_by == approved_by:     # separation of duties
        return "rejected: maker and checker must differ"
    return f"paid {amount} to {to}"

# a clerk invents a fake supplier and approves it himself
print(pay(90000, "Sharma Traders", "vikram", "vikram"))

# the normal way: one person makes, another approves
print(pay(12000, "Gupta Steel", "vikram", "meena"))

Output:

rejected: maker and checker must differ
paid 12000 to Gupta Steel

Fraud now needs two dishonest people working together (called collusion), which is much rarer than one.

Problem 3: defence in depth

A jewellery shop doesn't trust one lock: there's a shutter and lock, CCTV and an alarm, and a safe inside. Many independent layers, so one failure isn't the end. That's defence in depth.

Jewellery shop Bank account
Shutter and lock (can be cut) Password (can be stolen)
CCTV and alarm (a separate check) OTP to your phone
A safe inside (limits the loss) A daily transfer limit

Demo 3: one layer vs three

def password_ok(r): return r["password"] == "chai@123"
def otp_ok(r):      return r["otp"] == "4821"
def limit_ok(r):    return r["amount"] <= 10000

def transfer(r, layers):
    for layer in layers:
        if not layer(r):
            return f"blocked by {layer.__name__}"
    return f"sent {r['amount']}"

# a scammer got the password on a call, not the OTP
r = {"password": "chai@123", "otp": "0000", "amount": 50000}

all3 = [password_ok, otp_ok, limit_ok]
print("only password:", transfer(r, [password_ok]))
print("three layers: ", transfer(r, all3))

Output:

only password: sent 50000
three layers:  blocked by otp_ok

The password layer failed completely, and the next layer still held. Design as if every layer will fail someday. (layer.__name__ is the function's name, here otp_ok.)

Problem 4: when things break (fail secure vs fail safe)

A gym's smart lockers ask a permission server "is this person allowed?" on every tap. One day the server goes down: no yes, no no. What should the lock do? A programmer decides this in advance, in code.

An exception is Python's way of signalling an error; raise creates one and except catches it.

Demo 4: fail open

def ask_permission_server(user):
    raise TimeoutError("permission server not responding")

def can_open_locker(user):
    try:
        return ask_permission_server(user)
    except Exception as e:
        print("error:", e)
        return True     # "don't block people if it's down"

print("stranger opens locker:", can_open_locker("stranger"))

Output:

error: permission server not responding
stranger opens locker: True

The failure opened the door: fail open.

Demo 4b: fail secure (fail closed)

def ask_permission_server(user):
    raise TimeoutError("permission server not responding")

def can_open_locker(user):
    try:
        return ask_permission_server(user)
    except Exception as e:
        print("error:", e)
        return False    # fail secure: no answer = no entry

print("stranger opens locker:", can_open_locker("stranger"))

Output:

error: permission server not responding
stranger opens locker: False
Fail secure (fail closed) Fail safe
Protects the asset Protects people
Bank vault: power cut → stays locked Fire exit: power cut → unlocks
Login check: error → deny Lift doors: fault → open at a floor
Firewall: crash → block traffic Traffic lights: fault → blink amber

Both are correct for different things. Saltzer and Schroeder's security version is fail-safe defaults: "default situation is lack of access". In security code: when you don't know, the answer is no.

Problem 5: secure by default, secure by design, complete mediation

A new Wi-Fi router out of the box:

# insecure by default: safe only if the user changes ALL of it
admin_password = "admin"
remote_admin  = True
wps_button    = True
auto_update   = False
# secure by default: safe even if the user changes nothing
import secrets
admin_password = secrets.token_urlsafe(12)   # unique per device
remote_admin  = False
wps_button    = False
auto_update   = True
print("printed on this router's label:", len(admin_password), "characters")

Output:

printed on this router's label: 16 characters
  • Secure by default: the settings out of the box are already the safe ones. Most people never change defaults, so defaults are the security for most users.
  • Secure by design: security is planned from the first sketch (requirements, architecture, threat model in episode 7), not bolted on at the end. Like designing a building with fire exits instead of drilling them in later.

(WPS, Wi-Fi Protected Setup, is a push-button pairing feature with a history of weaknesses; "remote admin" lets the router be managed from the internet.)

Demo 5: checked once, trusted forever

A cache is a quick store of earlier answers, kept to save time.

allowed = {"ravi", "meena"}
cache = {}

def open_file(user):
    if user not in cache:            # checked only ONCE
        cache[user] = user in allowed
    return "opened" if cache[user] else "denied"

print("monday:", open_file("ravi"))
allowed.remove("ravi")               # Ravi leaves the job
print("tuesday:", open_file("ravi"))

Output:

monday: opened
tuesday: opened

Demo 5b: check every access

allowed = {"ravi", "meena"}

def open_file(user):
    if user in allowed:              # checked EVERY time
        return "opened"
    return "denied"

print("monday:", open_file("ravi"))
allowed.remove("ravi")               # Ravi leaves the job
print("tuesday:", open_file("ravi"))

Output:

monday: opened
tuesday: denied

Complete mediation: check permission on every access to every object, every time ("control access to every object"). To mediate is to stand in the middle and check. If you must cache for speed, keep the cache short-lived and clear it the moment permissions change.

Problem 6: hiding the method (open design)

A startup "protects" messages with a secret method: shift every letter forward by 3, so meet becomes phhw. They feel safe because nobody knows the method. But methods leak: an ex-employee, a curious student, a guess.

Demo 6: the attacker tries every shift

ord(c) gives a letter's number (a is 97); chr(n) turns a number back into a letter; % 26 wraps z back to a.

# our "secret" method: shift every letter by a number
def shift(text, k):
    out = ""
    for c in text:
        if c.isalpha():
            c = chr((ord(c) - 97 + k) % 26 + 97)
        out += c
    return out

secret = shift("meet me at the gate", 3)
print("sent:", secret)

# the attacker tries every possible shift
for k in range(1, 26):
    guess = shift(secret, -k)
    if " the " in guess:          # looks like English?
        print("key", k, "->", guess)

Output:

sent: phhw ph dw wkh jdwh
key 3 -> meet me at the gate

Cracked in 25 tries. Two failures at once: the whole security was hiding the method, and there were only 25 possible keys (the set of all possible keys is called the keyspace; this one is tiny).

  • Security through obscurity: a system that's safe only while its design stays secret. Obscurity can add a small delay, but must never be the only protection.
  • Open design: the system stays safe even if everyone knows exactly how it works; only the key is secret.
  • Kerckhoffs's principle: in 1883, Auguste Kerckhoffs wrote in La Cryptographie Militaire (Journal des Sciences Militaires) that "the design of a system should not require secrecy, and compromise of the system should not inconvenience the correspondents". Method public, key secret.

Modern encryption follows it: AES (Advanced Encryption Standard, episode 11) is completely public and studied by everyone, and its smallest key size has 2¹²⁸ possible keys, not 25. Public designs get reviewed by thousands of experts; secret ones get reviewed only by the attacker who finally figures them out.

Problem 7: simple, usable, small

Real life Principle Meaning
"A new 16-character password every week", so people stick it on the monitor Psychological acceptability Security must be easy to use correctly, or people will work around it
A wiring closet nobody understands hides the one bad cable Economy of mechanism Keep designs small and simple: fewer places for mistakes to hide, easier to check
Switch off the unused fax line Minimise attack surface Remove features, services and accounts you don't need (episode 1)

The 1975 list: Saltzer and Schroeder

In 1975, Jerome Saltzer and Michael Schroeder published The Protection of Information in Computer Systems, with eight design principles. You invented most of them today:

# Principle In one line Today's demo
1 Economy of mechanism Keep the design small and simple The wiring closet
2 Fail-safe defaults Default = no access The locker returns False
3 Complete mediation Check every access Ravi's cached "yes"
4 Open design Don't rely on the design being secret The shift cipher
5 Separation of privilege Require two keys Maker-checker
6 Least privilege Minimum needed for the job The intern
7 Least common mechanism Share as little as possible between users; every shared part is a path between them (episode 30)
8 Psychological acceptability Easy to use correctly The sticky note

They also mentioned two more ideas: work factor (compare the cost of breaking a mechanism with the attacker's resources; 25 keys is a tiny work factor) and compromise recording (reliably record that a break-in happened, like a broken seal).

Common mistakes (and what they print)

Mistake Real output Why Fix
"intern": {"read", "delete"} intern deleted salary.xlsx … left: set() More privilege than the job needs Least privilege: "intern": {"read"}
except Exception: return True stranger opens locker: True Fail open: an error grants access Fail secure: on error, return False
if user not in cache: cache[user] = ... tuesday: opened (Ravi already left) Checked once, trusted forever Complete mediation: check every access
"Nobody knows our shift method" key 3 -> meet me at the gate Obscurity, and only 25 keys Open design: public method, huge secret key
One layer (password only) only password: sent 50000 No defence in depth Add independent layers (OTP, limits)
Shipping admin_password = "admin" Most users never change it Insecure by default Unique per-device secrets, risky features off

Mini project: a tiny policy checker

Combine four principles in one function: deny by default, least privilege (role permissions), complete mediation (check on every call), and fail secure (any error means no).

ROLES = {"intern": {"read"}, "editor": {"read", "write"}, "owner": {"read", "write", "delete"}}
USERS = {"asha": "owner", "ravi": "intern", "meena": "editor"}

def allowed(user, action):
    try:
        role = USERS[user]                 # KeyError if unknown user
        return action in ROLES[role]       # least privilege
    except Exception:
        return False                       # fail secure

for user, action in [("ravi", "read"), ("ravi", "delete"), ("meena", "write"),
                     ("asha", "delete"), ("stranger", "read")]:
    print(f"{user:<9} {action:<7} {'allow' if allowed(user, action) else 'deny'}")

Output:

ravi      read    allow
ravi      delete  deny
meena     write   allow
asha      delete  allow
stranger  read    deny

Practice

  1. Add an "editor" role to Demo 1 that can read and write, but not delete. What does delete_all("editor") print?
  2. Add a fourth layer to Demo 3: new_device_ok, which blocks if r["device"] isn't in a set of known devices.
  3. How many keys would the shift cipher have if it shifted pairs of letters by two independent numbers (0-25 each)? Is that "huge"?
  4. Fail secure or fail safe? (a) an electronic door lock on a server room during a power cut; (b) a hospital ward's door during a fire alarm; (c) a payment API whose fraud check times out.
  5. Name the principle broken: (a) a shared admin password used by the whole IT team; (b) a website that hides its admin page at /secret-admin-9431 with no login; (c) a phone app asking for contacts, camera and location to show a calculator.
Solutions

1.

files = {"report.pdf", "salary.xlsx", "logo.png"}
PERMS = {"owner": {"read", "write", "delete"},
         "editor": {"read", "write"},
         "intern": {"read"}}

def delete_all(user):
    for f in sorted(files):
        if "delete" in PERMS[user]:
            files.discard(f)
            print(f"{user} deleted {f}")
        else:
            print(f"{user} denied: {f}")

delete_all("editor")

Output:

editor denied: logo.png
editor denied: report.pdf
editor denied: salary.xlsx

2.

KNOWN = {"asha-phone"}

def password_ok(r):   return r["password"] == "chai@123"
def otp_ok(r):        return r["otp"] == "4821"
def limit_ok(r):      return r["amount"] <= 10000
def new_device_ok(r): return r["device"] in KNOWN

def transfer(r, layers):
    for layer in layers:
        if not layer(r):
            return f"blocked by {layer.__name__}"
    return f"sent {r['amount']}"

r = {"password": "chai@123", "otp": "4821", "amount": 5000, "device": "unknown-laptop"}
print(transfer(r, [password_ok, otp_ok, limit_ok, new_device_ok]))

Output:

blocked by new_device_ok
  1. 26 × 26 = 676 keys. Still tiny: a computer tries all of them instantly. Real keys have around 2¹²⁸ possibilities.
  2. (a) fail secure (protects the servers); (b) fail safe (protects people); (c) fail secure (decline or hold the payment).
  3. (a) accountability and least privilege (nobody knows who did what, and everyone has full power): give each admin their own account with only the access they need; (b) security through obscurity (and no complete mediation): require a login and an authorization check; (c) least privilege: ask only for permissions the feature needs.

Quick quiz

During a power cut, a bank's vault door stays locked, while the fire exit door unlocks. Which principle does the vault follow?

A. fail safe · B. fail secure · C. open design · D. least privilege

Answer

B, fail secure. The vault protects the asset by staying locked when something fails. The fire exit is fail safe: it protects people.

Interview questions

  1. What is least privilege, and how would you apply it to a service account? Give the account only the permissions its job needs (for example read-only access to one database table), nothing more, and remove them when no longer needed.
  2. Defence in depth: give a web application example. Input validation, parameterised queries, a least-privilege database user, a web application firewall, logging and alerts, and encrypted backups: each still helps when another fails.
  3. Fail secure vs fail safe? Fail secure keeps the asset protected when something breaks (deny on error); fail safe keeps people safe (unlock the fire exit). Security checks in software should fail closed.
  4. What's wrong with security through obscurity? Secrets about a design leak and can't be changed easily. Security should rest on keys that can be kept secret and rotated, with designs that survive public review (Kerckhoffs's principle). Obscurity can be an extra layer, never the only one.
  5. What is complete mediation, and how can caching break it? Checking authorization on every access. A cached "allowed" answer keeps working after permission is revoked unless the cache is short-lived and invalidated on change.
  6. Separation of duties vs least privilege? Least privilege limits what each person can do; separation of duties splits one risky task across people so no single person can complete it.
  7. What does secure by default mean for a product? The out-of-the-box configuration is the safe one: no default passwords, unnecessary features off, updates on, so users who change nothing are still safe.
  8. Name some of Saltzer and Schroeder's principles. Economy of mechanism, fail-safe defaults, complete mediation, open design, separation of privilege, least privilege, least common mechanism, psychological acceptability (1975).

Glossary

Term Meaning in plain words Example
Privilege A permission to do something read, write, delete, approve
Least privilege Give each user and program only the minimum privileges its job needs The intern can only read
Need to know See information only if your work needs it The cook doesn't enter the cash room
Blast radius How much damage one failure or stolen account can do A read-only account can't delete files
Separation of duties Split a risky task so no one person can complete it alone Maker-checker for payments
Maker-checker One person makes a request, a different person approves it Vikram makes, Meena approves
Separation of privilege Saltzer and Schroeder's name for requiring two keys A two-key bank locker
Collusion Two or more people secretly working together to cheat Needed to beat maker-checker
Defence in depth Several independent layers of protection Password + OTP + daily limit
Exception Python's signal that something went wrong TimeoutError("permission server not responding")
Fail open On failure, access is granted except: return True
Fail secure / fail closed On failure, access is denied; protects the asset A vault stays locked in a power cut
Fail safe On failure, the system protects people A fire exit unlocks in a power cut
Fail-safe defaults The default is no access; access needs explicit permission Deny unless a rule allows
Secure by default Out-of-the-box settings are already safe Unique router password, updates on
Secure by design Security planned from the first design, not added at the end A building designed with fire exits
Cache A quick store of earlier answers, kept for speed The cache dict in Demo 5
Complete mediation Check permission on every access, every time Ravi denied on Tuesday
Security through obscurity Safe only while the design stays secret The "secret" shift-by-3 method
Open design Safe even when everyone knows how it works AES is fully public
Kerckhoffs's principle The design shouldn't need to be secret; only the key should (1883) Method public, key secret
Key The secret value that makes a public method produce a private result The shift amount, 3
Keyspace The set of all possible keys 25 shifts; 2¹²⁸ AES-128 keys
AES Advanced Encryption Standard, today's main public encryption method Episode 11
Economy of mechanism Keep security designs small and simple Fewer places for bugs to hide
Psychological acceptability Security must be easy to use correctly Passwords people can remember, or a password manager
Minimise attack surface Remove features, services and accounts you don't need Switch off the unused fax line
Least common mechanism Share as little as possible between users Separate data per customer
Work factor The effort an attacker needs, compared with their resources 25 guesses: tiny
Compromise recording Reliably recording that a break-in happened A broken seal, an audit log
Saltzer and Schroeder Authors of the 1975 paper listing eight design principles The Protection of Information in Computer Systems

Summary

  • Least privilege and need to know: minimum access, minimum data. Small blast radius.
  • Separation of duties: no one person completes a risky task alone (maker-checker).
  • Defence in depth: independent layers; assume each will fail someday.
  • Fail secure (fail closed) for security checks: when you don't know, the answer is no. Fail safe is for protecting people.
  • Secure by default and secure by design: safe out of the box, planned from the start.
  • Complete mediation: check every access; caches must not outlive permissions.
  • Open design / Kerckhoffs's principle: method public, key secret, keyspace huge. Security through obscurity is never enough.
  • Keep it simple (economy of mechanism), usable (psychological acceptability) and small (minimise the attack surface).
  • Saltzer and Schroeder wrote most of this down in 1975, and it's still true.

Next episode: threat actors and how attacks unfold: who attacks and why, the cyber kill chain, MITRE ATT&CK, TTPs, and indicators of compromise vs attack.

Sources: Wikipedia, "Saltzer and Schroeder's design principles" and a summary of the 1975 paper; Wikipedia, "Auguste Kerckhoffs" (La Cryptographie Militaire, 1883). Fetched 27 Oct 2026.