← Back to Learning Hub

Lesson 7: Secure Software Architecture I

Security Principles, Cryptography & Privacy by Design

75 minutes Year 12 Content High Exam Priority

Part 1: Homework 3 Review 10 min

Bug Hunt: Task 2C

Look at your Task 2C code. There's a subtle bug — can you spot it?

Your Task 2C Code (simplified)
for num in numbers:
    if num % 7 == 0:
        print(f"Found one divisible by 7!")
        break
    else:
        iterator_counter += 1
print("No terms divisible by 7")   

The Problem

The print("No terms divisible by 7") line is outside the loop — it runs no matter what, even when a match IS found. This is a common logic bug.

Two Ways to Fix It

Fix 1: Flag Variable Pattern

Use a boolean "flag" to track whether you found a match:

Fix 1: Flag Pattern
found = False                       # The flag starts as False

for num in numbers:
    if num % 7 == 0:
        print(f"Found: {num}")
        found = True                # Flip the flag
        break

if not found:                       # Only prints if flag was never flipped
    print("No terms divisible by 7")
Fix 2: Python's for...else (Pythonic)
for num in numbers:
    if num % 7 == 0:
        print(f"Found: {num}")
        break
else:                               # This 'else' belongs to the FOR loop
    print("No terms divisible by 7")  # Only runs if loop completes WITHOUT break

Python's for...else: The else block on a for loop runs only if the loop finished normally (no break). It's unusual — most languages don't have this — but it's perfect for "search and report" patterns.

Clarification: for vs while

Your homework answer was: "for is for one-time occasions." Let's sharpen that:

Use for when... Use while when...
You know how many times to loop You don't know how many times — loop until a condition changes
Iterating over a collection (list, string, range) Waiting for user input, game loops, polling
for item in items: while not done:
Example: "Check every student in the class" Example: "Keep asking until password is correct"

Connection to today's lesson: That "keep asking until password is correct" example? That's authentication — and that's exactly what we're covering today.

Part 2: Security Across the SDLC 5 min

Security Isn't a Phase — It's Every Phase

You already know the SDLC phases. The Year 12 twist: security must be built into every single phase, not bolted on at the end.

SDLC Phase Security Consideration
Requirements Define who can access what. What data is sensitive? What laws apply (e.g. Privacy Act)?
Specifications Specify encryption standards, password policies, data retention rules
Design Plan authentication system, authorisation levels, secure data flow
Development Validate all input, handle exceptions, use secure coding practices
Integration Secure APIs between components, test data flow between modules
Testing Security testing (SAST, DAST), penetration testing, vulnerability scanning
Installation Secure deployment, HTTPS configuration, environment variable protection
Maintenance Patch vulnerabilities, monitor logs, update dependencies

Exam Tip

  • A common HSC question: "Explain how security is integrated across the SDLC"
  • Don't just say "test for security" — show that security is considered at every phase

Part 3: CIA Triad Review + The AAA Model 15 min

Quick CIA Recap (from Lesson 3)

The three core security principles:

  • Confidentiality — Only authorised people can see the data
  • Integrity — Data hasn't been tampered with or corrupted
  • Availability — Systems are accessible when needed

Quick Check

  • A hacker changes a student's grade in the database. Which CIA principle is violated?
  • A DDoS attack takes down the school website. Which principle?
  • Someone reads another student's private messages. Which principle?

Answers

Reveal Answers
  • Grade change = Integrity (data was modified without authorisation)
  • DDoS = Availability (system is no longer accessible)
  • Reading messages = Confidentiality (data accessed by unauthorised person)

The AAA Model: Beyond the CIA Triad

CIA tells us what to protect. AAA tells us how to enforce it:

1. Authentication — "Who are you?"

Proving your identity to the system. Methods include:

  • Something you know — Password, PIN, security question
  • Something you have — Phone (SMS code), security key, smart card
  • Something you are — Fingerprint, face recognition, retina scan

Multi-Factor Authentication (MFA) combines two or more of these. For example: password (know) + SMS code (have).

2. Authorisation — "What are you allowed to do?"

After you prove who you are, the system checks your permissions:

  • Role-Based Access Control (RBAC) — Permissions based on your role (e.g. student, teacher, admin)
  • A student can view their own grades but can't edit them
  • A teacher can edit grades for their class but not other classes
  • An admin can access everything

3. Accountability — "What did you do?"

Tracking and recording actions so they can be reviewed later:

  • Audit logs — Record who did what, when, and from where
  • Non-repudiation — You can't deny an action if it's logged
  • Example: "User blake logged in at 3:42pm from IP 192.168.1.10"
  CIA (What to protect)          AAA (How to enforce it)
  ┌─────────────────┐           ┌──────────────────────┐
  │ Confidentiality │──────────▶│ Authentication       │
  │                 │           │ (Verify identity)    │
  ├─────────────────┤           ├──────────────────────┤
  │ Integrity       │──────────▶│ Authorisation        │
  │                 │           │ (Check permissions)  │
  ├─────────────────┤           ├──────────────────────┤
  │ Availability    │──────────▶│ Accountability       │
  │                 │           │ (Log everything)     │
  └─────────────────┘           └──────────────────────┘

Real-world example: Think about your school portal. You authenticate with your student ID + password. You're authorised to see your own marks but not other students'. Every login is logged for accountability.

How This Connects to Your Website

On Luis's tutoring site (the one you're reading this on), the login system uses all three:

  • Authentication: You enter your password, which is checked against a bcrypt hash
  • Authorisation: You can only see your dashboard, not other students'
  • Accountability: The server records login events with timestamps

Part 4: Cryptography, Hashing & Your Website Problem 20 min

The Problem with Your Sanguine Aetherium

Your website has a "secret password" feature — but the password is visible in the JavaScript source code. Anyone can right-click, view source, and see it.

Why? Because JavaScript runs client-side — in the user's browser. The user has full access to everything the browser receives.

Client-Side vs Server-Side Execution

This is a fundamental concept for understanding web security:

Client-Side (Browser) Server-Side (Server)
Runs on User's computer Website owner's server
Languages HTML, CSS, JavaScript Python, Node.js, PHP, Java
User can see code? Yes — View Source, DevTools No — code stays on the server
Safe for secrets? NEVER Yes — that's the whole point
Example Your Sanguine Aetherium password check Luis's tutoring login system

Golden Rule

Never put secrets in client-side code. No passwords, no API keys, no encryption keys. If the browser can see it, so can the user.

Encryption: Turning Data into Gibberish (Reversibly)

Encryption transforms readable data (plaintext) into unreadable data (ciphertext) using a key. With the right key, you can reverse it.

Symmetric Encryption (Same Key)

One key to encrypt AND decrypt. Like a padlock where the same key locks and unlocks it.

  • Algorithm: AES (Advanced Encryption Standard) — used worldwide
  • Speed: Fast — good for encrypting large amounts of data
  • Problem: How do you safely share the key with the other person?
  Symmetric Encryption (AES)
  ──────────────────────────

  "Hello Blake"  ──▶ [ AES + Key123 ] ──▶  "x8Kp2mQ..."
    (plaintext)        (encrypt)             (ciphertext)

  "x8Kp2mQ..."  ──▶ [ AES + Key123 ] ──▶  "Hello Blake"
    (ciphertext)       (decrypt)             (plaintext)

  Same key (Key123) used for both directions

Asymmetric Encryption (Two Keys)

Two mathematically related keys: a public key (shared freely) and a private key (kept secret). What one encrypts, only the other can decrypt.

  • Algorithm: RSA — used for HTTPS, digital signatures, secure email
  • Speed: Slower than symmetric — typically used for small data or to exchange symmetric keys
  • Solves: The key-sharing problem. You publish your public key; anyone can encrypt a message that only you can read.
  Asymmetric Encryption (RSA)
  ───────────────────────────

  Blake wants to send a secret message to Luis:

  "Secret msg"  ──▶ [ RSA + Luis's PUBLIC key ]  ──▶  "Qz9xW..."
    (plaintext)        (encrypt)                        (ciphertext)

  "Qz9xW..."   ──▶ [ RSA + Luis's PRIVATE key ] ──▶  "Secret msg"
    (ciphertext)       (decrypt)                        (plaintext)

  Anyone can encrypt with the public key.
  Only Luis can decrypt with his private key.

Hashing: One-Way Transformation

Hashing is NOT encryption. It's a one-way function — you can't reverse it.

Encryption Hashing
Reversible? Yes (with the key) No — one-way only
Purpose Protect data in transit/storage Verify data without storing the original
Output size Varies with input Always fixed length
Use case Sending a secret message Storing passwords
Hashing in Action
# Hashing is one-way: same input ALWAYS gives same output
# SHA-256 examples:
"blake2025"   → "a3f2b8c1d4e5..."   (always 64 hex characters)
"blake2026"   → "7x9m2k4p1q8..."   (completely different!)
"Blake2025"   → "r5t8w2y6n3a..."   (case matters!)

# You CAN'T go backwards:
"a3f2b8c1d4e5..."  → ???            (impossible to reverse)

How Password Verification Actually Works

The server never stores your actual password. Here's the flow:

When You Create an Account:

  1. You type password: "blake2025"
  2. Server hashes it: bcrypt("blake2025") → "$2b$10$xK..."
  3. Server stores ONLY the hash: "$2b$10$xK..."

When You Log In:

  1. You type password: "blake2025"
  2. Server hashes your input: bcrypt("blake2025") → "$2b$10$xK..."
  3. Server compares hashes: "$2b$10$xK..." == "$2b$10$xK..."
  4. They match → access granted!
  Password Verification Flow
  ──────────────────────────

  SIGN UP:
  "blake2025" ──▶ [ bcrypt hash ] ──▶ "$2b$10$xK..." ──▶ Store in database
                                         (hash only!)

  LOGIN:
  "blake2025" ──▶ [ bcrypt hash ] ──▶ "$2b$10$xK..."
                                            │
                                            ▼
                                       Compare ══▶ Match? ──▶ Access granted!
                                            ▲
                                            │
                            Database: "$2b$10$xK..."

Why bcrypt? The Salt.

A salt is random data added to the password before hashing. This means even if two users have the same password, their hashes are different.

  • Without salt: hash("blake2025") → same hash every time (attackers can use pre-computed "rainbow tables")
  • With salt: bcrypt("blake2025", random_salt) → different hash every time

bcrypt automatically generates and stores the salt inside the hash string.

Sandboxing

Sandboxing means running code in an isolated environment where it can't affect the rest of the system.

  • Browser tabs — Each tab is sandboxed; one tab can't access another's data
  • Virtual machines — Run an entire OS inside a sandbox for testing malware
  • Docker containers — Isolate applications from each other on a server
  • Mobile apps — Each app runs in its own sandbox (can't read other apps' files)

Solving Your Website Problem

  • Your current approach: Password in client-side JS → anyone can see it
  • Proper solution: Use a server to check the password (like Luis's site does)
  • Quick fix for GitHub Pages (no server): StatiCrypt — encrypts the entire HTML page with AES-256. The password decrypts the page in the browser. The actual content is never visible without the password.

Part 5: Privacy by Design + Input Validation 15 min

Privacy by Design: 7 Foundational Principles

Created by Dr. Ann Cavoukian. The idea: build privacy into the system from the start, don't add it as an afterthought.

  1. Proactive, not Reactive — Prevent privacy problems before they happen, don't wait for breaches
  2. Privacy as the Default — If the user does nothing, their data is still protected (opt-in, not opt-out)
  3. Privacy Embedded in Design — Privacy is part of the architecture, not a bolt-on feature
  4. Full Functionality — Privacy AND functionality, not one or the other (positive-sum, not zero-sum)
  5. End-to-End Security — Data is protected through its entire lifecycle (collection → storage → use → deletion)
  6. Visibility and Transparency — Users can see what data is collected and how it's used
  7. Respect for User Privacy — Keep the user's interests central. Give them control over their data.

Exam note: You don't need to memorise all 7 word-for-word. Know the key ideas: proactive, default privacy, embedded in design, transparency, and user control. Be able to apply them to a scenario.

Scenario: Privacy by Design in Practice

  • A social media app sets all new profiles to "Public" by default. Which principle does this violate?
  • A fitness app collects GPS data but never tells users. Which principle?
  • A school system deletes student records 2 years after graduation. Which principle does this follow?

Answers

Reveal Answers
  • Public by default = Violates Principle 2: Privacy as the Default (should be private until user chooses otherwise)
  • Hidden GPS collection = Violates Principle 6: Visibility and Transparency
  • Deleting old records = Follows Principle 5: End-to-End Security (data lifecycle management)

Input Validation & Sanitisation

Remember exception handling from Lesson 3? Input validation takes it further — never trust user input.

Input Validation

Checking that input meets expected criteria before processing it:

  • Type checking — Is it a number when you expect a number?
  • Range checking — Is the age between 0 and 150?
  • Length checking — Is the password at least 8 characters?
  • Format checking — Does the email contain an @ symbol?
  • Whitelist approach — Only allow known-good input (safer than trying to block bad input)

Input Sanitisation

Cleaning input by removing or escaping dangerous content:

  • Escaping — Converting special characters so they're treated as text, not code
  • Stripping — Removing HTML tags, script tags, or SQL keywords from input
Input Validation Example (Python)
def validate_age(user_input):
    """Validate that age is a reasonable integer."""
    # Type check
    try:
        age = int(user_input)
    except ValueError:
        return None, "Age must be a number"

    # Range check
    if age < 0 or age > 150:
        return None, "Age must be between 0 and 150"

    return age, "Valid"

# Test it
age, msg = validate_age("25")     # (25, "Valid")
age, msg = validate_age("abc")    # (None, "Age must be a number")
age, msg = validate_age("-5")     # (None, "Age must be between 0 and 150")
age, msg = validate_age("999")    # (None, "Age must be between 0 and 150")

Whitelist vs Blacklist

Whitelist (Allow List) Blacklist (Block List)
Approach Only allow known-good input Block known-bad input
Example "Username must be letters and numbers only" "Username cannot contain < or > or ;"
Security Stronger — you can't forget to block something Weaker — attackers find characters you forgot to block

Exam Tip

  • Whitelist > Blacklist — Always prefer whitelist validation in exam answers
  • Validation checks format. Sanitisation cleans the data. Both are needed.

Part 6: Knowledge Check 10 min

HSC-Style Questions

  • Q1: Distinguish between authentication and authorisation. (2 marks)
  • Q2: Explain why passwords should be hashed rather than encrypted when stored in a database. (3 marks)
  • Q3: A developer stores a user's password as password123 in a JavaScript file on a website. Identify TWO security issues with this approach. (2 marks)
  • Q4: Describe how Privacy by Design's "proactive, not reactive" principle could be applied when building a student records system. (2 marks)
  • Q5: Explain the difference between input validation and input sanitisation, giving an example of each. (3 marks)

Model Answers (Click to Reveal)

Q1: Authentication vs Authorisation

Authentication is the process of verifying a user's identity — confirming they are who they claim to be (e.g. entering a password or scanning a fingerprint).

Authorisation is determining what an authenticated user is permitted to do — their access level and permissions (e.g. a student can view grades but not edit them).

Q2: Hashing vs Encrypting Passwords

Hashing is a one-way function — it cannot be reversed, so even if attackers access the database, they cannot recover the original passwords. Encryption is reversible — if an attacker obtains the decryption key, all passwords are exposed. With hashing, verification works by hashing the login attempt and comparing it to the stored hash, so the original password is never needed or stored.

Q3: Password in JavaScript File

Issue 1: JavaScript runs client-side, meaning users can view the source code and see the password in plaintext through browser developer tools.

Issue 2: The password is stored in plaintext rather than being hashed, so it is immediately usable if discovered — there is no cryptographic protection.

Q4: Proactive Privacy in Student Records

Before building the system, the developer would conduct a privacy impact assessment to identify what student data is collected, who can access it, and potential risks. Security measures such as encryption, access controls, and data minimisation (only collecting what is necessary) would be built into the system's architecture from the start, rather than being added after a data breach occurs.

Q5: Validation vs Sanitisation

Input validation checks whether input meets expected criteria and rejects it if not. Example: checking that an email address contains an @ symbol and a domain name before accepting it.

Input sanitisation modifies input by removing or escaping dangerous characters so it can be safely processed. Example: converting <script> tags in user comments to harmless text so they display as text rather than executing as code.

What You've Learned Today

  • Homework bug fix — Flag pattern and for...else for search-and-report
  • for vs whilefor when you know the iterations, while when you don't
  • Security across the SDLC — Security at every phase, not just testing
  • CIA Triad — Confidentiality, Integrity, Availability (review)
  • AAA Model — Authentication, Authorisation, Accountability
  • Client-side vs Server-side — Never put secrets in client-side code
  • Encryption — Symmetric (AES, same key) vs Asymmetric (RSA, public/private keys)
  • Hashing — One-way, used for password storage (bcrypt with salt)
  • Sandboxing — Isolated execution environments
  • Privacy by Design — 7 principles, build privacy in from the start
  • Input Validation — Check format, type, range, length (whitelist > blacklist)
  • Input Sanitisation — Escape or remove dangerous content

Curriculum Progress

  • Year 12 Secure Software Architecture module — Part 1 complete
  • ~24 NESA content items covered in this lesson
  • HSC Outcomes: SE-12-04 (full), SE-12-07 (partial — continued in next lesson)

Next lesson: Secure Software Architecture II — Vulnerabilities & Testing. We'll cover real attack types (XSS, SQL Injection, CSRF), security testing (SAST, DAST, penetration testing), and how to write defensive code.

Homework Before Next Lesson

Security Analysis Tasks

Task 1: Fix Your Website Password

Look at the password feature on your Sanguine Aetherium website. Write a short paragraph explaining:

  • Why the current approach is insecure (use the terms from today's lesson)
  • Which CIA principle it violates
  • Two ways you could fix it (one with a server, one without)

Task 2: AAA Scenario Analysis

Pick any app or website you use regularly. Identify examples of:

  • Authentication — How does it verify your identity?
  • Authorisation — What can you do vs what you can't?
  • Accountability — How are actions tracked?

Task 3: Input Validation Practice

Write a Python function validate_password(password) that checks:

  • At least 8 characters long
  • Contains at least one uppercase letter
  • Contains at least one number
  • Returns (True, "Valid") or (False, "reason")
Hint for Task 3

You can use .isupper(), .isdigit(), and the any() function:

any(char.isupper() for char in password) — returns True if at least one character is uppercase.

← Back to Blake's Learning Hub