Computer Science · Book 5 · Bachelor Year 3

University Computer Science — Year 3

University Computer Science — Year 3 · Bachelor Year 3

29Software Security

Cryptography protects data on its way between programs. Most attacks do not break it: they go around it, through the programs themselves. A login desk that copies a name without checking its length, a query built by pasting text into SQL, a page that shows a comment as it was typed, a service that does what it is asked with more rights than the asker has: each is a programming error that turns into a way in. This chapter takes the library’s own toy programs, a login desk in C and a small web app in Python, finds each error, shows exactly what it allows, and fixes it. Every attack runs on the chapter’s own code, on the reader’s own machine, against nothing else: understanding an attack is the way to write code that resists it.

You already know

A function’s local variables live in its stack frame, below the saved frame pointer and the return address. A write past the end of an array is a buffer overflow: undefined behaviour, which the compiler may assume never happens, and AddressSanitizer reports at run time (Year 1 volume). HTTP requests carry cookies, which a server sets to recognise a returning browser (grade 10 and Year 2 volumes). SQL queries come from the Year 1 volume, Rust’s checked indexing from the Year 2 volume, and password hashing from Chapter 28.

29.1 Threat models

Definition 29.1 (Threat model, asset, adversary, trust boundary, attack surface)

A threat model is a written description of what a system must protect, from whom, and how it can be attacked. An asset is something of value the system must protect: data, a service, a reputation. An adversary is someone who wants to harm an asset, described by its goals and by what it can do, its attack model (Definition 27.1). A trust boundary is a line in the system across which data or commands pass from a less trusted part to a more trusted one. The attack surface is the set of places where an adversary can send data or commands into the system.

The library’s web app lets readers log in, read and post comments, and renew their loans. Its assets are the accounts and their passwords, the loans, the comments and the app’s files; its adversaries are an outsider on the network and, more often, a reader with an account who wants more than a reader’s rights. Every request from a browser crosses a trust boundary; so does every value passed on to the database, the operating system’s shell or the file system, which interpret what they receive. The STRIDE checklist names six kinds of threat to look for at each boundary: spoofing an identity, tampering with data, repudiation of an action, information disclosure, denial of service and elevation of privilege.

The toy app’s data flows and its trust boundaries, dashed. Data from a browser crosses the first boundary; text that the app passes to the database, the file system or the shell crosses the second, where another program interprets it.
The toy app’s data flows and its trust boundaries, dashed. Data from a browser crosses the first boundary; text that the app passes to the database, the file system or the shell crosses the second, where another program interprets it.

29.2 Memory-safety errors and their defences

The login desk is a C program. Its check function copies the typed name into a 16-byte array with strcpy, which copies until the terminating zero byte, however far that is.

static int check(const char *typed) {
    int is_admin = 0;
    char name[16];
    strcpy(name, typed);  // BUG: no length check
    printf("hello %s\n", name);
    return is_admin;
}
Listing 29.1. The login desk’s check. The flag is_admin is never set to 1 anywhere in the program. code/bachelor-3/29-software-security/listings/toy_login.c

Definition 29.2 (Stack smashing, integer overflow vulnerability)

Stack smashing is a buffer overflow in a stack frame that overwrites other data of the frame: another local variable, the saved frame pointer or the return address. An integer overflow vulnerability is an arithmetic overflow in a size or index computation, which makes a later check or allocation use a wrong, usually too small, value.

Where the bytes go depends on the frame the compiler built. The disassembly of check gives it.

$ gcc -std=c17 -O0 -fno-stack-protector -c toy_login.c -o plain.o
$ objdump -d --no-show-raw-insn plain.o | grep -A9 '<check>:' | grep 'rbp)' | cut -f2-
mov    %rdi,-0x28(%rbp)
movl   $0x0,-0x4(%rbp)
mov    -0x28(%rbp),%rdx
lea    -0x20(%rbp),%rax
$ gcc -std=c17 -O0 -fstack-protector-all -c toy_login.c -o canary.o
$ objdump -d --no-show-raw-insn canary.o | grep -A16 '<check>:' | grep 'rbp)' | cut -f2-
mov    %rdi,-0x38(%rbp)
mov    %rax,-0x8(%rbp)
movl   $0x0,-0x24(%rbp)
mov    -0x38(%rbp),%rdx
lea    -0x20(%rbp),%rax
lea    -0x20(%rbp),%rax
Output 29.1. The plain build keeps is_admin at -0x4(%rbp) and name at -0x20(%rbp). The build with the stack protector moves is_admin below the array, to -0x24, and stores the canary at -0x8.
The frame of check in the two builds, from , with offsets from the frame pointer in bytes. In the plain build the 29th byte of a name lands in is_admin; with the protector the array sits just below the canary, and the flag is out of reach below it.
The frame of check in the two builds, from Output 29.1, with offsets from the frame pointer in bytes. In the plain build the 29th byte of a name lands in is_admin; with the protector the array sits just below the canary, and the flag is out of reach below it.

So the 29th byte typed lands in the low byte of is_admin, and the terminating zero of a 28-byte name lands there too, harmlessly. The program is run with five names; the captured runs, like every compiled program in this book, have address randomisation turned off, which this attack does not need anyway.

$ gcc -std=c17 -O0 -fno-stack-protector -o toy_login toy_login.c -lm && ./toy_login
 3 bytes typed: hello ada
reader desk
16 bytes typed: hello adaadaadaadaadaa
reader desk
17 bytes typed: hello adaadaadaadaadaad
reader desk
28 bytes typed: hello adaadaadaadaadaadaadaadaadaX
reader desk
29 bytes typed: hello adaadaadaadaadaadaadaadaadadX
admin desk opened
Output 29.2. Names of 16, 17 and 28 bytes already write past the array, without visible effect. The 29-byte name opens the admin desk.

Nothing in the output warns that the first overflows happened: undefined behaviour need not show. AddressSanitizer, whose shadow memory marks the bytes around each array, stops at the first one, the 16-byte name, whose terminating zero is the 17th byte.

$ gcc -std=c17 -O0 -g -fsanitize=address -o toy_login_asan toy_login_asan.c -lm && ./toy_login_asan
 3 bytes typed: hello ada
reader desk
=================================================================
==1000==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7fffffffe400 at pc 0x7ffff74544bf bp 0x7fffffffe3a0 sp 0x7fffffffdb48
WRITE of size 17 at 0x7fffffffe400 thread T0
    #0 0x7ffff74544be in __interceptor_strcpy ../../../../src/libsanitizer/asan/asan_interceptors.cpp:440
    #1 0x5555555553b6 in check toy_login.c:10
    #2 0x5555555555a7 in main toy_login.c:21
Address 0x7fffffffe400 is located in stack of thread T0 at offset 48 in frame
    #0 0x555555555318 in check toy_login.c:7

  This frame has 1 object(s):
    [32, 48) 'name' (line 9) <== Memory access at offset 48 overflows this variable
Output 29.3. The same input under AddressSanitizer: a write of 17 bytes at offset 48 of the frame, just past name, which occupies offsets 32 to 47. Some lines are left out.

Elias Levy’s article “Smashing the Stack for Fun and Profit”, published in 1996 under the name Aleph One, described how an overflow that reaches the return address makes a function return into code of the attacker’s choice. Years before, in November 1988, the Morris worm had spread partly through a buffer overflow in a network service, the finger daemon. Defences have accumulated since, each against one step of such an attack.

Definition 29.3 (Stack canary, address-space layout randomisation, non-executable memory, control-flow integrity)

A stack canary is a value that the compiler stores between a function’s arrays and its saved registers on entry, and checks on exit, ending the program if it changed. Address-space layout randomisation (ASLR) loads the stack, the heap, the libraries and the program at random addresses at each run, so that an attacker cannot know where code or data lies. Non-executable memory marks the stack and the heap as not executable, so that bytes written there cannot run as instructions. Control-flow integrity (CFI) checks at run time that every indirect jump, call and return goes to a target that the program’s code allows.

StackGuard introduced the canary in 1997 and published it in 1998; GCC’s -fstack-protector guards the functions that have arrays of 8 bytes or more, and -fstack-protector-all guards them all; a guard found overwritten ends the program with a message. The PaX project published the first ASLR, for Linux, in July 2001.

$ gcc -std=c17 -O0 -fstack-protector-all -o toy_login_canary toy_login_canary.c -lm && ./toy_login_canary
 3 bytes typed: hello ada
reader desk
16 bytes typed: hello adaadaadaadaadaa
reader desk
17 bytes typed: hello adaadaadaadaadaad
reader desk
28 bytes typed: hello adaadaadaadaadaadaadaadaadaX
*** stack smashing detected ***: terminated
[exit status -6]
Output 29.4. With a canary in every function: the 28-byte name overwrites the canary, and the check at the function’s exit ends the program with signal 6, an abort, before check returns.

A canary detects the overflow after it happened, at the function’s exit; it cannot stop an overflow that changes a variable used before the exit. Here the compiler also moved the flag below the array, which is what saves it. The fix is a length check before the copy, or a function that takes the size of the destination.

static int check(const char *typed) {
    int is_admin = 0;
    char name[16];
    if (strlen(typed) >= sizeof name) {  // the name and its final '\0' must fit
        printf("name too long, refused\n");
        return 0;
    }
    strcpy(name, typed);
    printf("hello %s\n", name);
    return is_admin;
}
Listing 29.2. The length checked before the copy: the name and its terminating zero must fit in the array. code/bachelor-3/29-software-security/listings/toy_login_fixed.c
$ gcc -std=c17 -O0 -fno-stack-protector -o toy_login_fixed toy_login_fixed.c -lm && ./toy_login_fixed
 3 bytes typed: hello ada
reader desk
16 bytes typed: name too long, refused
reader desk
17 bytes typed: name too long, refused
reader desk
28 bytes typed: name too long, refused
reader desk
29 bytes typed: name too long, refused
reader desk
Output 29.5. The same five names: every name of 16 bytes or more is refused before the copy, and the desk stays a reader’s.

Sizes can also be wrong before any copy. A file reader that computes count * sizeof(loan) in 32 bits allocates 8 bytes for 229+12^{29} + 1 records, since (229+1)⋅8=232+8(2^{29} + 1) \cdot 8 = 2^{32} + 8 wraps around to 8, and then writes as many records as count says.

$ gcc -std=c17 -O0 -g -fsanitize=address -o short_alloc short_alloc.c -lm && ./short_alloc
count 536870913, bytes 8
=================================================================
==1000==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x502000000018 at pc 0x555555555359 bp 0x7fffffffe5d0 sp 0x7fffffffe5c0
WRITE of size 4 at 0x502000000018 thread T0
    #0 0x555555555358 in main short_alloc.c:19
0x502000000018 is located 0 bytes to the right of 8-byte region [0x502000000010,0x502000000018)
allocated by thread T0 here:
    #0 0x7ffff74b4887 in __interceptor_malloc ../../../../src/libsanitizer/asan/asan_malloc_linux.cpp:145
    #1 0x5555555552ed in main short_alloc.c:16
Output 29.6. The integer overflow, then the heap overflow it causes, at the second record: AddressSanitizer reports a write just past an 8-byte region. Some lines are left out.

Rust removes the error at its root: indexing and slicing are checked, and a copy that does not fit stops the program with a panic, before a single byte is written outside the array.

fn check(typed: &str) -> bool {
    let is_admin = false;
    let mut name = [0u8; 16];
    name[..typed.len()].copy_from_slice(typed.as_bytes()); // checked: panics if too long
    println!("hello {}", String::from_utf8_lossy(&name[..typed.len()]));
    is_admin
}
Listing 29.3. The same copy in Rust: name[..typed.len()] panics if the name is longer than 16 bytes. code/bachelor-3/29-software-security/listings/bounds.rs
$ rustc --edition 2021 -O -o bounds bounds.rs && ./bounds
 3 bytes typed: hello ada
reader desk
16 bytes typed: hello adaadaadaadaadaa
reader desk
17 bytes typed: panicked at bounds.rs:10:9:
range end index 17 out of range for slice of length 16
[exit status 101]
Output 29.7. The 16-byte name fits exactly, since Rust strings need no terminating zero; the 17-byte name panics. The panic message is printed by a hook that leaves out the thread’s number.

The checks cost a few instructions, and the canary a few more; AddressSanitizer, a debugging tool, more than doubles the size of main, and its documentation gives a typical slowdown of 2 times.

$ build toy_login.c -fno-stack-protector
toy_login.c        -fno-stack-protector   main:  58 instructions, file  16280 bytes
$ build toy_login.c -fstack-protector-all
toy_login.c        -fstack-protector-all  main:  67 instructions, file  16328 bytes
$ build toy_login_fixed.c -fno-stack-protector
toy_login_fixed.c  -fno-stack-protector   main:  69 instructions, file  16288 bytes
$ build toy_login.c -fsanitize=address
toy_login.c        -fsanitize=address     main: 136 instructions, file  21896 bytes
Output 29.8. Each build at -O2: the instructions of main, into which check is inlined, and the size of the program file. Some lines are left out.

29.3 Injection and validation of input

Definition 29.4 (SQL injection, parameterised query, command injection, path traversal)

An SQL injection happens when text from an adversary is pasted into the text of an SQL statement, so that it changes the statement instead of being a value in it. A parameterised query sends the statement with placeholders, and the values separately, so that the database parses the statement before it sees any value. A command injection is the same error with a command line given to a shell. A path traversal is a file name from an adversary that, joined to a directory, names a file outside it, for instance with ...

def login_unsafe(name, password):
    h = hashlib.sha256(password.encode()).hexdigest()
    sql = f"SELECT name, role FROM users WHERE name = '{name}' AND pw_hash = '{h}'"
    print("   SQL:", sql[:72] + ("..." if len(sql) > 72 else ""))
    return db.execute(sql).fetchone()


def login_safe(name, password):
    h = hashlib.sha256(password.encode()).hexdigest()
    sql = "SELECT name, role FROM users WHERE name = ? AND pw_hash = ?"
    return db.execute(sql, (name, h)).fetchone()  # the values never become SQL text
Listing 29.4. Two logins: one builds the SQL text with the typed name in it; the other passes the name and the hash as parameters. To stay short, the toy hashes with plain SHA-256, not with the slow salted hash a real desk needs. code/bachelor-3/29-software-security/listings/login_sql.py
$ python login_sql.py
name 'ada', password 'correct horse':
   SQL: SELECT name, role FROM users WHERE name = 'ada' AND pw_hash = '4104d36f8...
   unsafe -> ('ada', 'reader')
   safe   -> ('ada', 'reader')
name 'ada', password 'wrong':
   SQL: SELECT name, role FROM users WHERE name = 'ada' AND pw_hash = '8810ad581...
   unsafe -> None
   safe   -> None
name "admin' --", password 'anything':
   SQL: SELECT name, role FROM users WHERE name = 'admin' --' AND pw_hash = 'ee0...
   unsafe -> ('admin', 'admin')
   safe   -> None
Output 29.9. The name admin' -- closes the string, and -- turns the rest of the statement, the password check, into a comment. The parameterised query looks for a user of that exact name and finds none.

Python’s sqlite3 documentation says to always use placeholders instead of string formatting to bind values; the subprocess documentation gives the same warning for a command run with shell=True.

$ python cmd_inject.py
shell=True:
Report: Spring loans
SECOND COMMAND RAN
list form:
Report: Spring loans; echo SECOND COMMAND RAN
Output 29.10. With shell=True, the semicolon in the title starts a second command, here a harmless second echo; with a list of arguments, the title reaches echo as one argument.

Definition 29.5 (Input validation, output encoding)

Input validation checks, where data enters, that it has the expected form, preferably against a list of what is allowed, and rejects the rest. Output encoding rewrites data where it leaves for an interpreter, according to that interpreter’s syntax, so that every character is read as data: HTML escaping for a web page, quoting for a shell, placeholders for SQL.

The two are complementary: validation rejects what makes no sense for the application, a loan of −3-3 weeks or a name of 4,000 characters, but a valid name can still contain a quote, and only encoding at the point of use, for the language of that place, makes it harmless.

29.4 Web vulnerabilities and their fixes

Definition 29.6 (Cross-site scripting, cross-site request forgery, session token)

Cross-site scripting (XSS) happens when a page includes text from an adversary without encoding it, so that a script in the text runs in other users’ browsers with the rights of the site. Cross-site request forgery (CSRF) happens when a page on another site makes a user’s browser send a request to the site, which the browser accompanies with the user’s cookies, so that the site performs it as the user. A session token is the random value that a site gives a browser after login, usually in a cookie, and that identifies the session in every later request.

The toy app serves its pages on 127.0.0.1, port 45291, with Python’s http.server. Its tokens come from secrets. With safe=False it shows comments as they were typed; with safe=True it escapes them with html.escape, which turns <, >, & and quotes into entities.

    def page(self, cookie):
        s = self.sessions.get(cookie)
        show = html.escape if self.safe else (lambda text: text)  # the escape point
        items = "".join(
            f"<li>{show(who)}: {show(text)}</li>\n" for who, text in self.comments
        )
        token = f'<input type="hidden" name="csrf" value="{s["csrf"]}">' if s else ""
        form = (
            f'<form method="post" action="/comment">{token}<input name="text"></form>'
        )
        return 200, f"<ul>\n{items}</ul>\n{form}"
Listing 29.5. The page: the comments, escaped or not, and a form that carries the session’s CSRF token. code/bachelor-3/29-software-security/listings/webapp.py
$ python xss_demo.py
unsafe app, the comment in Ada's page:
  <li>eve: <script>alert(document.cookie)</script></li>
  Ada's cookie flags: []
safe app, the comment in Ada's page:
  <li>eve: &lt;script&gt;alert(document.cookie)&lt;/script&gt;</li>
  Ada's cookie flags: [' HttpOnly', ' SameSite=Strict']
Output 29.11. Eve’s comment reaches Ada’s page as a script in the unsafe app, and as text in the safe one. The safe app also marks the session cookie HttpOnly and SameSite=Strict.
Stored cross-site scripting. The comment is harmless in the database; it becomes code only when it is pasted into HTML, so that is where it must be encoded, for that context.
Stored cross-site scripting. The comment is harmless in the database; it becomes code only when it is pasted into HTML, so that is where it must be encoded, for that context.

An HttpOnly cookie cannot be read by scripts, which limits what an injected script can steal; a content security policy, sent by the server, tells the browser which scripts a page may run, and is a standard defence against such injection. Both reduce the damage; neither replaces the encoding.

For CSRF, the app writes a random token, tied to the session, into each of its forms, and refuses any state-changing request whose form does not carry it. A page on another site can make Ada’s browser send the request, with her cookie, but cannot read the app’s pages to learn the token.

$ python csrf_demo.py
unsafe app, forged request: 200 loan of ada renewed for 52 weeks
   Ada's own request: 200 loan of ada renewed for 2 weeks
safe app, forged request: 403 refused: missing or wrong CSRF token
   Ada's own request: 200 loan of ada renewed for 2 weeks
Output 29.12. The forged renewal is performed by the unsafe app and refused by the safe one; Ada’s own request, from the app’s form, passes in both.

A browser also refuses to send a SameSite=Strict cookie with a request that comes from another site; the token check does not depend on the browser’s help.

29.5 Authentication and access control

Authentication establishes who sends a request: a password, checked against its slow salted hash as in Chapter 28, then a session token, random, long, sent only over HTTPS, and invalidated at logout. Access control then decides what that user may do.

Definition 29.7 (Access-control matrix, access-control list, capability, role-based access control)

An access-control matrix has a row for each subject (a user or a process), a column for each object (a file, a route, a record), and in each cell the rights of the subject on the object. An access-control list (ACL) is a column of the matrix, stored with its object. A capability is an unforgeable reference that names an object and some rights on it; the capabilities a subject holds form its row. Role-based access control gives rights to roles, such as reader or librarian, and roles to users.

The toy app’s access-control matrix. A column is an object’s access-control list; a row, the capabilities its subject holds.
The toy app’s access-control matrix. A column is an object’s access-control list; a row, the capabilities its subject holds.
def may(subject, obj, right):
    return right in acls.get(obj, {}).get(subject, "")


def export_confused(caller, out):
    """Checks the service's own right to write `out`, not the caller's."""
    if not may("export-service", out, "w"):
        return "refused"
    return f"report written to {out}"


def export_fixed(caller, out):
    """Acts for the caller: both the service and the caller must hold the right."""
    if not (may("export-service", out, "w") and may(caller, out, "w")):
        return "refused"
    return f"report written to {out}"
Listing 29.6. The export service writes a report to a file named by its caller. The confused version checks its own rights; the fixed one also checks the caller’s. code/bachelor-3/29-software-security/listings/acl.py

Definition 29.8 (Least privilege, privilege separation, confused deputy)

Least privilege gives every subject only the rights its legitimate purpose needs. Privilege separation splits a program into parts with different rights, so that the part exposed to adversaries holds few. A confused deputy is a program that holds rights of its own and, acting for a less privileged caller, uses them on an object the caller chose, which the caller could not have touched itself.

Saltzer and Schroeder stated least privilege among their design principles in 1975, and Hardy named the confused deputy in 1988, from a compiler that wrote its output to a file named by its user, a billing file included.

$ python acl.py
ACL of fines.csv: {'export-service': 'rw'}
capabilities of eve: {'loans.csv': 'r', 'eve-notes.txt': 'rw'}
eve asks for eve-notes.txt:
   confused: report written to eve-notes.txt; fixed: report written to eve-notes.txt
eve asks for fines.csv:
   confused: report written to fines.csv; fixed: refused
Output 29.13. The matrix read both ways. Eve cannot write fines.csv, but the confused export service writes it for her; the fixed one refuses.

The ACL check asked the wrong question: may the service write the file? The right question is whether the request may, and a capability system answers it by construction, since the caller hands the deputy the capability for the output file, and cannot hand one it does not hold.

Facts as of 2026

OWASP’s Top Ten, a list of the most critical security risks of web applications, was first published in 2003 and has been revised regularly since, the latest edition in 2025. It is a useful checklist for a threat model, not a substitute for one.

29.6 Exercises

Exercise 29.1 ★

The town hall publishes a form where residents book a room; the bookings go into a database, a clerk approves them in a back-office page, and a nightly script e-mails the confirmations. List the assets, two adversaries, and the trust boundaries that a booking crosses.

Solution

Solution of Exercise 29.1.

Assets: the bookings and the rooms’ availability; the residents’ personal data, names and e-mail addresses; the clerk’s back-office account, whose approvals are binding; the town hall’s e-mail sender, whose messages residents trust. Adversaries: a resident who wants rooms without approval, or to block others’ bookings; an outsider who wants the personal data or to send e-mail in the town hall’s name. A booking crosses the network into the web form’s server; then from the server into the database, as SQL; then from the database into the back-office page, where the clerk’s browser renders it as HTML; then from the database into the nightly script and on to the mail server, where its fields become e-mail headers and text. Each crossing hands the booking to a new interpreter, and each needs its own encoding.

Exercise 29.2 ★

A reader’s name is shown in an HTML page, inside an HTML attribute, in a URL query string, in an SQL query and in a shell command. For each place, say what must be done to the name, and why validation alone at login is not enough.

Solution

Solution of Exercise 29.2.

In HTML text, escape &, < and >. Inside an attribute, also escape the quotes, and always quote the attribute. In a URL query string, percent-encode it, with urllib.parse.quote. In SQL, pass it as a parameter. In a shell command, pass it as one element of an argument list, with no shell. Validation at login cannot replace these: a perfectly valid name, O’Brien, contains a quote that matters in SQL and in an attribute and nowhere else, and the code that validates does not know every place where the name will be used. Each encoding belongs to the place of use.

Exercise 29.3 ★

Ada wants to let the reading club read one of her notes for a week, and to revoke that later. Compare doing it with an access-control list and with a capability. Which makes it easier to know who can read the note? To revoke?

Solution

Solution of Exercise 29.3.

With an ACL, Ada adds the club with right r to her note’s list, and removes it after a week. Who can read the note is in one place, the list, and revocation is one deletion. With a capability, Ada gives the club a reference with right r. The club can pass it on, so who can read is whoever holds a copy, which nobody can list; revoking it needs a capability designed for that, one that goes through a forwarder Ada can disable, or one with an expiry date. Capabilities are better at delegation without a central authority, and at avoiding the confused deputy; ACLs at reviewing and revoking.

Exercise 29.4 ★

Predict what the safe app prints for the comment Tom & Jerry's <b>"best"</b>, after html.escape with its default arguments.

Solution

Solution of Exercise 29.4.

The output is

Tom &amp; Jerry&#x27;s &lt;b&gt;&quot;best&quot;&lt;/b&gt;

With its default quote=True, html.escape also replaces both kinds of quote; the browser shows the original text, tags included, and makes nothing bold. A test checks the string.

Exercise 29.5 ★★

serve_buggy in exercises/ex5_path.py serves files from a public folder by joining the requested name to it. Show a name that reads a file outside the folder, then write serve_fixed, which resolves the path, follows symbolic links, and refuses anything outside the folder.

Solution

Solution of Exercise 29.5.

The name ../secret.txt joined to public names public/../secret.txt, which is secret.txt next to the folder. serve_fixed resolves the joined path, which removes every .. and follows symbolic links, and refuses it unless it lies inside the resolved folder and is a regular file. A test reads a file outside the folder through the buggy version and checks that the fixed one refuses ../secret.txt, ../public/../secret.txt, an absolute path, the folder itself, an empty name, and a symbolic link inside the folder that points outside. Checking the name for .. instead would miss the link and absolute paths.

Exercise 29.6 ★★

Write the CSRF check of the toy app: a random token per session, a function that compares the token of a form with the session’s in constant time, and a decorator require_csrf that refuses state-changing requests without it. Why must the comparison be in constant time?

Solution

Solution of Exercise 29.6.

exercises/ex6_csrf.py: new_session stores, for a random cookie value, the user and a second random token; csrf_ok looks up the session of the cookie and compares the form’s token with hmac.compare_digest; require_csrf wraps a handler and answers 403 when the app is in safe mode and the check fails. The app uses it on its two state-changing routes. A comparison that stops at the first differing character takes longer the more leading characters are right, so an attacker who can submit guesses and time the answers could recover the token character by character; a constant-time comparison gives the timing nothing to reveal. A test checks the refusals with no token and with a wrong one.

Exercise 29.7 ★★

From the second half of Output 29.1, compute the shortest name that makes the canary build abort, and check it. Can any name, of any length, make this build open the admin desk?

Solution

Solution of Exercise 29.7.

In the canary build name starts at -0x20 and the canary at -0x8: byte 24 of the name is the canary’s lowest byte. A 24-byte name writes its terminating zero there and passes, so that byte of the canary must already be zero; a 25-byte name changes it, and the program aborts. A test runs both. No name can open the admin desk in this build: is_admin lies at -0x24, below the array, and strcpy only writes upwards from the array’s start.

Exercise 29.8 ★★

Prove that a parameterised query cannot change its statement’s structure: model the statement as a sequence of tokens produced by the SQL tokenizer from the text with placeholders, and show that the values, bound after tokenizing, appear in the parse tree only as literals. Why does this argument fail for string formatting?

Solution

Solution of Exercise 29.8.

Facts used: the SQL engine tokenizes and parses the statement text before binding. The statement text with placeholders is fixed by the program; the tokenizer turns it into a sequence of tokens in which each ? is one placeholder token, and the parser builds a tree from these tokens alone, where each placeholder is a leaf of type literal. Binding then attaches a value to each placeholder leaf, without tokenizing it. So whatever its characters, quotes or -- included, a value can only fill a literal leaf: the tree, hence the statement’s structure, is the same for all values. With string formatting, the value’s characters are part of the text that the tokenizer reads, so a quote in the value ends the string token and the following characters become keywords, as admin' -- does in Output 29.9. A property test checks, on 200 random names given Ada’s password, that the safe login never returns anyone but Ada.

Exercise 29.9 ★★

Explain how count * sizeof(loan) wraps around in short_alloc.c, and write alloc_loans(count), which refuses any count whose size would not fit in 32 bits. Which counts are refused?

Solution

Solution of Exercise 29.9.

count * sizeof(loan) is computed in 32 bits, modulo 2322^{32}: (229+1)⋅8=232+8≡8(2^{29} + 1) \cdot 8 = 2^{32} + 8 \equiv 8. The allocation gets 8 bytes, and the loop writes 229+12^{29} + 1 records of 8 bytes. The function alloc_loans of the exercise’s program refuses when count > UINT32_MAX / sizeof(loan), a test done before the multiplication, which cannot overflow. ⌊(232−1)/8⌋=536,870,911\lfloor (2^{32} - 1)/8 \rfloor = 536{,}870{,}911, so every count from 229=536,870,9122^{29} = 536{,}870{,}912 up is refused; 2292^{29} itself would have wrapped to 0. The program tries 3, 1,000,000 and 229+12^{29} + 1, and a test checks the refusal of the last.

Exercise 29.10 ★★★

Model the HTML tokenizer in text content as a machine with a data state, which emits characters as text, and states that < enters (tag open) and & enters (character reference). Prove that after html.escape, every input is emitted as text, character for character, and that the rendered text equals the input.

Solution

Solution of Exercise 29.10.

Facts used: in the model, the data state emits every character other than < and & as text and stays in the data state; & starts a character reference, which emits the character it names and returns to the data state; < enters the tag-open state. html.escape replaces &, <, >, " and ' by references that start with &, end with ;, and contain only letters, digits and #. Its output therefore contains no < at all, so the machine never leaves the data state except for references. By induction on the output: every character not inside a reference is emitted as itself, and each reference, introduced only by escaping, is emitted as the one character it replaced; an & of the input has become &amp;, so it cannot start a reference by accident. So the emitted text is exactly the input. A property test checks, on random strings, that the escaped text contains no <, > or double quote, and that unescaping gives the input back. The argument holds for text content only: inside a script element or an unquoted attribute the tokenizer is in other states, and other encodings are needed.

Exercise 29.11 ★★★

Design least-privilege roles for the toy app among visitor, reader, librarian and administrator, for the routes view page, post comment, renew own loan, renew any loan, delete comment, export loans and manage users. Write the matrix, a function that every route calls, and argue why the administrator should not hold the librarian’s rights.

Solution

Solution of Exercise 29.11.

exercises/ex11_roles.py: a visitor may only view; a reader may also comment and renew their own loans; a librarian may also renew any loan, delete comments and export the loans; an administrator may view and manage users, and nothing else. Every route calls allowed(role, route), which denies anything not granted, so an unknown role or a new route is refused by default. The administrator’s account is the most attacked and the most powerful; keeping loans and comments out of its rights means a stolen administrator session cannot quietly change loans, and an administrator who wants to must give himself a second role, which leaves a trace. The test checks the visitor’s row, that every granted right names a real route, and two refusals.

Exercise 29.12 ★★★

Run aslr.py. Which bits of the addresses change from run to run, and which do not? Explain why ASLR does not stop the flag overwrite of Output 29.2, what it does make harder, and why canaries are still needed.

Solution

Solution of Exercise 29.12.

In the randomised runs the stack addresses and main’s address change at each run. main % 4096 stays 361: the program’s mapping moves by whole 4096-byte pages, and offsets within it do not. The stack array’s address modulo 4096 changes too (2656, 1232, 2000, 560, 2032), because Linux also shifts the top of the stack by a random amount smaller than a page, in steps of 16 bytes: only its low 4 bits stay fixed. With setarch -R every run gives the same addresses.

$ python aslr.py
randomised:
  name at 140,720,688,708,192  main at  96,760,483,565,929  main % 4096 = 361
  name at 140,730,386,433,232  main at 106,144,412,774,761  main % 4096 = 361
  name at 140,734,437,201,872  main at 102,128,039,309,673  main % 4096 = 361
  name at 140,732,059,415,088  main at 100,602,471,461,225  main % 4096 = 361
  name at 140,722,140,227,568  main at 102,788,499,808,617  main % 4096 = 361
setarch -R:
  name at 140,737,488,348,656  main at  93,824,992,235,881  main % 4096 = 361
  name at 140,737,488,348,656  main at  93,824,992,235,881  main % 4096 = 361
  name at 140,737,488,348,656  main at  93,824,992,235,881  main % 4096 = 361
  name at 140,737,488,348,656  main at  93,824,992,235,881  main % 4096 = 361
  name at 140,737,488,348,656  main at  93,824,992,235,881  main % 4096 = 361
Output 29.14. Five runs of the same program with ASLR and five without, on the author’s laptop: the addresses of a stack array and of main, in decimal.

The flag overwrite uses only offsets inside one frame, 28 bytes from name to is_admin, which ASLR does not change, so it works as before. ASLR makes harder the attacks that need an absolute address: returning into injected code or into a library function, or overwriting a pointer with the address of something. It can be defeated by any bug that leaks one address, since the rest of a mapping follows from it. A canary does not depend on hiding anything from the attacker: a contiguous overwrite of the return address must pass over the canary and changes it, so the two defences protect against different steps and are used together.

29.7 Weekend problem

Problem 29.1

Weekend problem — The library’s login desk

The login desk of Listing 29.1 has run for years. A reader reports that a long name once opened the admin desk. The problem reconstructs the attack from the compiled program, then applies each defence in turn.

Part I — The frame layout.

  1. In the first half of Output 29.1, which instruction stores 0 in is_admin, and at what offset?
  2. Which instruction passes the address of name to strcpy, and at what offset is name?
  3. What does -0x28(%rbp) hold?
  4. How many bytes lie between the start of name and the start of is_admin? How many of them belong to name?
  5. Why might the compiler leave 12 bytes unused between them?
  6. Does the C standard promise this layout? What does that mean for the attack?

Part II — The minimal input.

  1. Which byte of the typed name lands in the low byte of is_admin?
  2. Why does the 28-byte name not open the desk, although it writes 29 bytes?
  3. Give the length of the shortest name that opens the admin desk, and check it in Output 29.2.
  4. Would the name X repeated 29 times work? A name whose 29th byte is the zero byte?
  5. Which lengths of name write past name without changing the outcome?
  6. The integer is 4 bytes and the machine little-endian. Which value does is_admin hold after the 29-byte name ending in X?

Part III — Each defence in turn.

  1. What does the canary build do with the same five names, and why does it stop at the fourth?
  2. Why can no name reach is_admin in the canary build?
  3. Which input does AddressSanitizer stop at, and why that one?
  4. What does the bounds-checked C version print for the five names?
  5. What does the Rust version do, and why is it 17 bytes and not 16 that fail there?
  6. Which of these four would you ship, and which would you use only while testing?

Part IV — What each catches and what it costs.

  1. From Output 29.8, how many instructions does the canary add to main? The length check?
  2. How much does AddressSanitizer add to the instructions and to the program file, and what else does it need at run time?
  3. Which defences detect the overflow, and which prevent it?
  4. Which would catch an overflow that changes a variable that is used before the function returns?
  5. What does the length check cost at run time, per login?
  6. Sum up: how many bytes does the attack need and why, what does the canary do with it, and what does the bounds check cost?
Solution

Solution of Problem 29.1.

1. movl $0x0,-0x4(%rbp): is_admin is at offset −4-4 from the frame pointer.

2. lea -0x20(%rbp),%rax, whose result is then moved to %rdi, the first argument: name starts at offset −32-32.

3. The function’s argument typed, the pointer to the line, stored from %rdi on entry.

4. 32−4=2832 - 4 = 28 bytes, of which 16 are name and 12 are unused.

5. The compiler is free to arrange the frame. Here it keeps the array on a 16-byte boundary and places the integer at the top; the rest is left unused.

6. No: the standard says nothing about the order or the gaps of local variables, and a write past the array is undefined behaviour. The attack depends on this compiler, these flags and this program; the canary build shows another layout from the same source.

7. Byte 28, counting from 0: the 29th character typed.

8. A 28-byte name occupies bytes 0 to 27 and strcpy writes its terminating zero at byte 28, the low byte of is_admin, which was already 0.

9. 29 bytes: the last line of Output 29.2, 29 bytes ending in X, opens the admin desk.

10. Yes: any 29-byte name works, since its 29th byte is not zero. A name cannot have a zero 29th byte: strcpy stops at the first zero, so such a name would be shorter.

11. 16 to 28 bytes: they write between 17 and 29 bytes, past the 16 of name, into the gap or the zero byte of is_admin.

12. Its bytes are 58 00 00 00 from the lowest address up: X, then the terminating zero, then the two bytes left at 0. Little-endian, that is 0x58=88\mathrm{0x58} = 88, non-zero, so true.

13. It greets the first three and aborts on the fourth, the 28-byte name, which writes bytes 24 to 28 of name’s region and so changes the canary; the check at the end of check ends the program before the result is used.

14. The protector moved is_admin below the array, at −36-36, and strcpy writes only upwards from name.

15. At the 16-byte name: its terminating zero is the 17th byte written, at offset 48 of AddressSanitizer’s frame, one past name’s region from 32 to 47; the shadow memory marks the bytes after the array as unusable.

16. It greets ada, refuses the four longer names as too long, and opens no admin desk.

17. It greets the 3-byte and the 16-byte name, then panics on the 17-byte name and exits with status 101. A Rust string carries its length and needs no terminating zero, so 16 bytes fit exactly.

18. Ship the length-checked version, compiled with the stack protector and run with ASLR, as defences in depth; or the Rust version. Use AddressSanitizer while testing: it finds the overflow at its first byte but costs time, memory and a run-time library.

19. The canary adds 67−58=967 - 58 = 9 instructions to main; the length check 69−58=1169 - 58 = 11.

20. 136−58=78136 - 58 = 78 instructions, more than doubling main, and 21,896−16,280=5,61621{,}896 - 16{,}280 = 5{,}616 bytes of program file; at run time it also needs its library and shadow memory, and runs about 2 times slower according to its documentation.

21. The canary and AddressSanitizer detect the overflow and stop the program; the length check and Rust’s checked copy prevent it, by refusing before anything is written.

22. AddressSanitizer, which checks each write, and the two bounds checks, which refuse before writing. The canary is checked only at the function’s exit, after the changed variable was used.

23. One strlen over at most 255 bytes and one comparison per login, next to a printf and a read from the terminal: nothing that a measurement could separate from noise.

24. The attack needs 29 bytes: the frame puts is_admin 28 bytes above the start of the 16-byte array, so the 29th byte typed sets its low byte. With the stack protector, the flag moves below the array, and an overflow long enough to reach the canary ends the program with an abort. The length check refuses every name that does not fit, for 11 instructions in main and one strlen per login.

Terms defined in this chapter

See all 1050 terms in the glossary