Operating Systems · Lecture Notes

Chapter 13: Security

The operating system is the guardian of every resource on a computer. It decides which process may read which file, which user may log in, and which code runs in kernel mode. If those decisions are wrong, even the best scheduler or the fastest file system is worthless: data leaks, gets tampered with, or becomes unavailable. These notes first define the goals and threats of security. They then present the cryptographic tools an operating system relies on: encryption, hashing, signatures, certificates, and TLS. The protection section covers the access matrix, access control lists, capabilities, and the principle of least privilege. Formal models and covert channels follow. The final sections treat authentication, memory-safety vulnerabilities, malware, and today's defenses: sandboxes, containers, mandatory access control, and secure boot.

Learning outcomes

Goals and threats
Distinguish the goals of confidentiality, integrity, and availability, the types of attack, and the profiles of attackers.
Cryptography
Explain symmetric and asymmetric encryption, hash functions, digital signatures, certificates, and the TLS handshake; work through a Diffie-Hellman exchange step by step.
Protection
Read the access matrix in its ACL and capability forms; apply least privilege, setuid, and Linux capabilities.
Formal models
Apply the Bell-LaPadula and Biba rules; explain why covert channels cannot be closed completely.
Authentication
Compare salted slow password hashes, MFA, TOTP, and FIDO2 passkeys.
Attacks and defenses
Recognize memory-safety errors, TOCTOU, and malware; recognize canaries, NX, ASLR, CFI, sandboxing, and secure boot.

13.1Security goals and threats

Before protecting a system, we have to say what is being protected, against whom, and for what purpose. This section introduces the three basic goals of security, the kinds of events that violate them, and the attackers behind those events. It ends with the overall architecture of defense: layered defense and the trusted computing base.

13.1.1Security and protection

Operating-systems textbooks distinguish two closely related notions. Protection consists of mechanisms inside the system: rules that determine which process may access which object with which right, and that enforce those rules. File permission bits, the read-only bit in a page table, and the split between kernel and user mode are all protection mechanisms. Security is a broader question. How well does the system withstand deliberate attacks and accidents, from inside and outside? Even if the protection mechanisms work flawlessly, the system is not secure when a password is stolen, an administrator is tricked, or no backup was made.

This distinction has a practical consequence. Protection is a subsystem that the operating system implements directly and whose correctness can be proved. Security covers people, networks, hardware, and every bug in the software; it can never be fully achieved, and we can only raise the cost of an attack. These notes treat the two together. Goals and threats come first, then protection mechanisms. At the end we describe the attacks that try to get past those mechanisms and the defenses developed against them.

13.1.2The CIA triad

The goals of security are usually summed up in three words. Because of their initials, the three are called the CIA triad (Figure 13.1).

Definition 13.1

Confidentiality means that data can be read only by authorized parties. Integrity means that data can be modified only by authorized parties and only through authorized channels. Availability means that legitimate users can reach the data and the service whenever they need them.

ConfidentialityconfidentialityIntegrityintegrityAvailabilityavailabilityAssetdata · service · hardwareno unauthorized readingservice stays upno unauthorized changeViolation:disclosure (espionage, leak)Violation:denial of service (DoS)Violation: tampering, forged records, encryption for ransom
Figure 13.1: The CIA triad. The protected asset may be data, a service, or hardware; violating each goal is a distinct kind of harm.

Each goal has a matching kind of violation. A breach of confidentiality is disclosure: a company's customer database is leaked, or spyware copies e-mail. A breach of integrity is tampering: a student changes his grade record, or an attacker replaces a system program with his own version. A breach of availability is denial of service: a web server is swamped with fake requests, or ransomware encrypts a disk and makes it unusable.

The three goals are not independent, and sometimes they conflict. Keeping copies of data in three countries improves availability, but it also raises the number of places where a leak can occur to three. Encrypting a disk improves confidentiality; if the key is lost, the data becomes inaccessible forever. Security design is therefore a matter of balancing the goals.

Two more goals are often added to the triad. Authenticity means that a message or a user can be verified to come from the claimed source. Accountability means that it can be proved afterwards who performed an action. Accountability has two tools: audit logs and non-repudiation. With non-repudiation, a person cannot deny a signed document later by saying “I did not sign it.” This is the real benefit of a digital signature.

Example 13.1

Consider four events involving the records on a hospital's file server. Which goal does each violate?

  1. An employee opens and reads the test results of a celebrity out of curiosity. The data did not change and the service did not stop, but an unauthorized person read it. This is a confidentiality violation.
  2. An attacker changes a patient's blood type. The data that gets read is now wrong, and nobody notices. This is an integrity violation, and it can be more dangerous than a confidentiality violation.
  3. Ransomware encrypts all files; doctors cannot reach the records for hours. The data did not leave the building and its content was not corrupted, but it cannot be used. This is an availability violation.
  4. A doctor later claims not to have written a prescription, and the records contain no trace that would refute this. Accountability is missing. If prescriptions were signed with the doctor's private key, denial would be impossible.

13.1.3Threat, vulnerability, attack, and exploit

Four words are easily confused in the language of security, but each is a separate link in a chain (Figure 13.2).

Definition 13.2

A threat is a possible harm. A vulnerability is the weakness that makes the harm possible. An attack is an attempt to use the vulnerability. An exploit is the code or technique that carries out that attempt.

Threatpossible harmVulnerabilityweaknessAttackattempt to exploitExploitcode / techniqueBreachloss of CIApatching fixes the vulnerability, authentication the attack, canary/NX the exploit, backups limit the consequence of the breach
Figure 13.2: The chain from threat to breach. Each link has its own defense: patching addresses the vulnerability, authentication the attack, canaries and NX the exploit, and backups limit the consequence of the breach.

An example makes the chain concrete. “Theft of customer data” is a threat. An unchecked input field in a web application is a vulnerability. The attacker's writing a specially crafted query into that field is an attack. The query itself, that is, the string or program that triggers the vulnerability, is the exploit. If the database is finally exfiltrated, confidentiality has been violated.

The value of the chain view is that a defense can be placed at every link. Patching removes the vulnerability. Strong authentication makes it harder for the attacker to get into the system. Measures such as stack canaries and non-executable pages stop the exploit from working. Backups limit the consequence of a breach even when everything else fails. Even if the defense at one link is broken, the later links remain in play.

As in the slides, breaches can be grouped into seven categories (Table 13.1). The first three correspond directly to the CIA goals. The next four undermine those goals indirectly.

Table 13.1: Categories of breach.
CategoryDefinitionExample
Breach of confidentialityUnauthorized reading of dataLeak of a credit-card database
Breach of integrityUnauthorized modification of dataRecord tampering in a grading system
Breach of availabilityDestruction of data or serviceRansomware encrypting a disk
Theft of serviceUnauthorized use of resourcesMining cryptocurrency on a compromised server
Denial of service (DoS/DDoS)Blocking legitimate useSYN flood from a botnet
MasqueradingPretending to be someone elsePassword stolen by phishing
Privilege escalationGaining more authority than one is entitled toBecoming root through a bug in a setuid program

In a denial of service (DoS) attack the goal is not to read or modify data. The attacker keeps the system so busy that it cannot answer legitimate requests. A TCP server keeps a half-open connection record for every connection request. The attacker sends thousands of fake requests (SYNs) per second and never completes the handshake. The table fills up and real users cannot connect. If the attack comes from thousands of compromised machines at once, it is called a distributed denial of service (DDoS) attack. Blocking a single source address then does not help either.

In masquerading, the attacker takes on the identity of another user or machine. Privilege escalation is when an ordinary user or process reaches administrator rights by exploiting a bug. For an operating system this is the most dangerous category, because with administrator rights all the other protections can be switched off.

13.1.4Network attacks

Almost every computer today is connected to a network, and the channel through which the operating system talks to the outside world is part of the attack surface. Security textbooks traditionally describe these attacks with three characters. Alice and Bob are two parties who want to talk. Eve (the eavesdropper) is a passive attacker who only listens. Mallory is an active attacker who can modify messages. If the channel is unencrypted and unauthenticated, all four attacks below are possible.

Eavesdropping
The passive attacker takes a copy of the traffic and reads it. Because it does not touch the messages, it is very hard to detect. It breaks confidentiality. The remedy is encryption: today this is mostly done by TLS.
Replay
The attacker captures a valid message and later resends it unchanged. The message may be encrypted and signed: the attacker does not need to read or modify it. If a “pay 1000 TL” message is processed twice, the damage doubles. The remedy is to attach a value that can be used only once to every message: a nonce, a timestamp, or a sequence number.
Man-in-the-middle (MITM)
The attacker steps in between the two parties and appears to each as the other. Alice thinks she is talking to Bob; in fact she is talking to Mallory. Mallory reads, modifies, and forwards the messages. Encryption alone is not a remedy: the party with whom Alice sets up the encrypted channel may be Mallory himself. The remedy is to authenticate the other party, which means certificates.
Session hijacking
After a user authenticates once, the server gives the user a session token, usually a cookie. If an attacker steals this token, he enters the session without knowing the password. The remedy is to send the token only over an encrypted channel (Secure), to keep scripts from reading it (HttpOnly), and to keep its lifetime short.
AliceclientBobserverEve / MalloryattackerAlice thinks she istalking to “Bob”Bob thinks he istalking to “Alice”man in the middle: reads and modifies
Figure 13.3: Man-in-the-middle: Mallory appears to each party as the other; he reads and modifies the messages.
AliceclientBobserverEve / MalloryattackerCookie: session=7f3a…enters the sessionwith the stolen cookie
Figure 13.4: Session hijacking: if the cookie issued after authentication is stolen, the attacker enters the session without a password.
Common mistake

Thinking that encryption prevents replay. The attacker can resend an encrypted message without decrypting it. If the receiver cannot tell that it has seen the same message before, it treats the second copy as valid too. Replay is prevented only by a single-use value attached to the message and by the receiver keeping track of those values.

13.1.5Attackers and accidental data loss

The strength of a defense is tuned to who the attacker is. Protecting a machine in a student lab against a curious friend is not the same job as protecting a bank's server against a state-sponsored group. Attackers fall roughly into four groups.

The curious insider
Has little technical knowledge and wants to “take a look” at someone else's e-mail or files. Usually exploits a permission mistake. The behavior is unethical and often illegal as well. Correct file permissions are mostly enough against this group.
The malicious employee
Has a legitimate account and authority on the system and abuses it. Can leak data, commit sabotage, or leave a logic bomb that triggers if he is fired. Sits inside the walls built against outside attackers, which makes this the hardest group to detect.
The cybercriminal
The motive is profit: ransomware, theft of identity and card data, renting out a network of compromised machines (a botnet). Today this is the most common threat. This group mostly uses known vulnerabilities that already have patches, and scans unpatched systems with automated tools.
State-sponsored groups
The literature calls them advanced persistent threats (APT). Their goals are military or commercial espionage and sabotage of critical infrastructure. They can stay inside silently for years. They use vulnerabilities that nobody yet knows (zero-days) and supply-chain attacks. Stuxnet, which appeared in 2010, was such a piece of software, aimed at uranium-enrichment centrifuges.

Attackers are not the only cause of data loss. Accidents lose far more data than attacks do (Table 13.2). A disk fails, an administrator formats the wrong disk, a laptop is left on a train. In Tanenbaum's wry example, even mice gnawing on backup tapes make the list.

Table 13.2: Causes of accidental data loss and countermeasures.
CauseExampleCountermeasure
Natural eventsfire, flood, earthquakegeographically separate backup
Hardware and software errorsdisk failure, CPU error, software bugRAID, checksums, versioning
Human errorwrong command, formatting the wrong disk, lost device3-2-1 backup, encrypted disk

The common backup rule is called 3-2-1: keep three copies of the data on two different media, with one copy kept in another location. Today a condition is added: the remote copy should be immutable. Ransomware also encrypts or deletes the backups it can reach over the network. An immutable copy survives this attack. In this way the same rule works against both accidents and attacks.

13.1.6Defense in depth

No defense is flawless. A firewall rule is written wrongly, an employee clicks a phishing e-mail, a new vulnerability is found in a library. So we do not rely on a single defense; defenses are arranged as nested layers. This principle is called defense in depth. It resembles the layout of medieval castles with a moat, a wall, an inner wall, and a keep: even if an attacker gets past one layer, he is stopped by the next (Figure 13.5).

Policy, training, physical securityNetwork: firewall, segmentationEndpoint: patches, EDR, disk encryptionOperating system: access control, sandboxApplication: input validation, memory-safe languageDataFirewallInternetPC 1PC 2PC 3only permitted connections pass
Figure 13.5: The layers of defense in depth (left) and a firewall in front of a network (right).

The layers run from the outside in as follows. At the outermost level are policies, user training, and physical security: the lock on the server-room door belongs to this layer. At the network layer, a firewall lets only permitted connections through; network segmentation also keeps the compromise of one segment from spreading to others. The endpoint layer has patches, endpoint detection and response (EDR) tools, and disk encryption. The operating-system layer provides access control and the sandbox. The application layer has input validation and memory-safe languages. At the innermost point stands the protected asset, the data.

Good practices are spread across these layers as well. Security updates are applied quickly, because most attacks use vulnerabilities whose patches came out long ago. Strong authentication and access control working with least privilege are the basic rule. Logs are kept and monitored; otherwise a breach may go unnoticed for months. Regular penetration tests look for the weak points of the defense in advance. Users are trained against phishing.

The zero trust approach, which has become common in recent years, is one step beyond defense in depth. In the traditional arrangement, the inside of the firewall was considered trusted: a machine inside could reach the other machines freely. Zero trust rejects this assumption. A request coming from inside the network goes through authentication and authorization just like one from outside. This makes lateral movement harder for an attacker who has slipped in.

13.1.7The trusted computing base

Every security claim rests on the assumption that some components work correctly. File permissions mean something only if the kernel code that checks them is free of bugs. The sum of these components is called the trusted computing base (Figure 13.6).

Definition 13.3

The trusted computing base (TCB) is the set of all hardware, firmware, and software components responsible for enforcing the system's security policy. A bug in the TCB can break the security of the whole system; a bug outside the TCB cannot violate the policy.

User spaceProcess AProcess BProcess CAttackerTrusted computing base (TCB)Reference monitorchecks every accessKernel, driversAuthenticationHardware (MMU, TPM)denied
Figure 13.6: Every access by user processes passes through the reference monitor inside the TCB. The attacker's request passes through it as well and is denied.

The heart of the TCB is the reference monitor. This component receives every access request, consults the policy, and decides to allow or deny. Three conditions must hold for a reference monitor to be trustworthy. First, it must be invoked on every access; a check that can be bypassed is as bad as no check at all. Second, it must be tamper-proof; user processes must not be able to modify its code or data. Third, it must be small enough for its correctness to be verified.

This third condition has an important consequence for operating-system design. The bigger the TCB, the higher the chance that it contains bugs. The Linux kernel has tens of millions of lines, and all of it, device drivers included, runs in kernel mode, that is, inside the TCB. This is why microkernels attract interest: by moving the file system and the drivers to user mode, they shrink the TCB. The seL4 microkernel goes further. Its roughly ten thousand lines of code have been formally proved to behave according to its specification.

Common mistake

Reading the TCB as “the components proved to be trustworthy.” The definition says the opposite: the TCB is the set of components that one has to trust. If a printer driver runs in kernel mode, it is part of the TCB, however sloppily it was written. The goal of secure design is to keep this set as small as possible.

13.2Cryptography

The operating system uses cryptography everywhere: when storing passwords, encrypting disks, verifying the signatures of update packages, protecting network connections, and checking the boot chain. This section introduces the basic tools needed to understand these uses. The goal is not to design ciphers. It is enough to know what each tool provides and what it does not.

13.2.1Basics of encryption

The purpose of encryption is to turn a readable message into a form that someone without the key cannot understand. The readable message is called plaintext (P), and its transformed form ciphertext (C). The function that performs the transformation is encryption E, and the function that reverses it is decryption D. Both use a key K (Figure 13.7).

Definition 13.4

Encryption makes data unreadable without the key. In symmetric or secret-key encryption, encryption and decryption use the same key:

C = E(P, K),   P = D(C, K)

Plaintext PEncrypt ECiphertext CDecrypt DPkey Kkey K (same)attacker sees CC = E(P, K) · P = D(C, K)
Figure 13.7: The symmetric encryption model. The attacker can see the ciphertext; without knowing the same K, he cannot obtain the plaintext.

The model assumes that the attacker can listen to the channel and see C. Does the attacker also know the encryption algorithm? By the principle Auguste Kerckhoffs set out in 1883, we must assume he does. Kerckhoffs's principle says that the security of a cryptosystem should rest only on the secrecy of the key. The algorithm may be public, and should be. A secret algorithm is sooner or later revealed by reverse engineering. A public algorithm, by contrast, is attacked for years by cryptographers all over the world; if it survives, it is considered trustworthy. This is why all of today's standard ciphers are open to everyone.

One consequence of Kerckhoffs's principle is the importance of the size of the key space. An attacker who knows the algorithm can try every key one by one. This method is called a brute-force attack. The old DES standard used a 56-bit key. In 1998, this space of 256 keys could be searched in a few days with special-purpose hardware. A 128-bit key space, by contrast, cannot be searched even with the computing power of the whole world. But a large key space alone is not enough; the next example shows why.

13.2.2Substitution cipher and frequency analysis

One of the oldest ciphers is the monoalphabetic substitution cipher. Each letter of the alphabet is replaced by a fixed other letter. The key is a permutation of the 26 letters. The key in the slides lists the letters starting from the top row of the keyboard: A → Q, B → W, C → E, and so on (Table 13.3).

Table 13.3: The key of the substitution cipher.
plainABCDEFGHIJKLM
cipherQWERTYUIOPASD
plainNOPQRSTUVWXYZ
cipherFGHJKLZXCVBNM
Example 13.2

Let us encrypt the word MERHABA with this key.

  1. The letter under M is D: M → D.
  2. E → T, R → K, H → I.
  3. A → Q, B → W, A → Q.

Result: MERHABA → DTKIQWQ. To decrypt, the table is read in the reverse direction: above the D in the ciphertext stands M. All three A's in the word have become Q.

AQBWCEDRETFYGUHIIOJPKALSMDNFOGPHQJRKSLTZUXVCWVXBYNZMPlaintextCiphertextMDETRKHIAQBWAQ
Figure 13.8: Encrypting MERHABA. The same plain letter always goes to the same cipher letter.

The key space of this cipher is huge: the number of permutations of 26 letters is 26! ≈ 4 × 1026, or about 288. A computer trying a billion keys per second would need billions of years to search this space. Even so, the cipher can be broken with a few lines of text, with pencil and paper. Why?

The fact that all three A's in the example became Q exposes the weakness. The cipher changes letters but does not change letter frequencies. In a Turkish text the most frequent letters are A, E, and İ (in English, E, T, and A). The most frequent letter in the ciphertext is very likely the image of A. Then the frequent two-letter and three-letter patterns (“ve”, “bir”, “ler”) are matched. After a few guesses the key emerges step by step. This method is called frequency analysis. It was first described in the ninth century by the Arab mathematician al-Kindi.

Common mistake

Equating a large key space with security. The key space is only a lower bound against brute force. If the structure of the cipher leaks the statistics of the plaintext, the attacker does not try keys one by one but uses the structure directly. This is why the 288 space is no help at all for the substitution cipher.

13.2.3Modern symmetric ciphers

Modern symmetric ciphers use one of two constructions to hide frequency information. Block ciphers split the data into fixed-size blocks and scramble each block over many rounds. The standard block cipher is AES (Advanced Encryption Standard, 2001). It uses 128-bit blocks and keys of 128, 192, or 256 bits. Today's processors have dedicated instructions for AES (AES-NI), and encryption reaches speeds of gigabytes per second. Stream ciphers instead generate a long random-looking byte sequence from the key and XOR it with the data. ChaCha20 is a common example of this kind; it is fast on phones that have no AES hardware.

It is not enough for a cipher to provide confidentiality alone. If an attacker flips bits of the ciphertext, the receiver gets a corrupted plaintext and may not notice. For this reason encryption today is always used together with an integrity check. This combined construction is called authenticated encryption. AES-256-GCM and ChaCha20-Poly1305 are two standard examples: they append a short authentication tag to the ciphertext. If even a single bit changes, the tag fails to match and the receiver rejects the message.

13.2.4Public-key cryptography

Symmetric encryption has a fundamental problem: the two parties must already share the same key. How do we share this key with a site we are connecting to for the first time on the Internet? Sending the key over the network amounts to giving it to everyone who is listening. In 1976, Diffie and Hellman gave a new answer to this question: two separate keys.

Definition 13.5

In public-key or asymmetric encryption, every user has a key pair. The public key is distributed to everyone; only the user knows the private key. A message encrypted with the public key can be decrypted only with the matching private key.

AlicesenderBobreceiverpublicPub_BprivatePriv_Bthe public key can be given to everyoneE(P, Pub_B)D(C, Priv_B)CWhat is encrypted with Pub_B can be decrypted only with Priv_B.
Figure 13.9: Alice encrypts with Bob's public key Pub_B; only Bob, who knows Priv_B, can decrypt the message.

When Alice wants to send Bob a secret message, she obtains Bob's public key and encrypts the message with it (Figure 13.9). Eve, who listens to the ciphertext, also knows Bob's public key, but she cannot decrypt the message with it. Decryption is possible only with the private key, and that key never leaves Bob's machine. So no previously shared secret is needed.

The mathematical basis of this arrangement is one-way trapdoor functions. Such a function is easy to compute in one direction and very hard to compute in the other. But if a secret piece of information (the trapdoor) is known, the reverse direction becomes easy too. In RSA (1977) the function is the product of large primes: multiplying two 1024-bit primes takes an instant, but there is no known fast way to factor the product. In elliptic-curve cryptography (ECC) the hard problem is the discrete logarithm on the curve.

Example 13.3

Let us follow RSA with toy-sized numbers. In real systems the numbers have hundreds of digits; the steps are the same.

  1. Key generation. Bob picks two primes: p = 3, q = 11. Their product is n = 33. φ = (p − 1)(q − 1) = 2 × 10 = 20. The public exponent is chosen as e = 3 (it has no common divisor with 20). The private exponent d is the number satisfying e · d ≡ 1 (mod 20): 3 × 7 = 21 ≡ 1, so d = 7. The public key is (n, e) = (33, 3) and the private key is d = 7.
  2. Encryption. Alice sends the message m = 4: c = me mod n = 43 mod 33 = 64 mod 33 = 31.
  3. Decryption. Bob computes cd mod n: 317 mod 33 = 4. The original message comes back.

Eve knows n = 33 and e = 3. To find d she needs φ, that is, she must know p and q. Factoring 33 is easy. Factoring a 2048-bit n, however, is beyond what today's computers can do. The values were verified with Python.

The price of asymmetric encryption is speed: it is a hundred to a thousand times slower than symmetric encryption (Table 13.4). So real systems use the two together. The asymmetric method does only a short job: it establishes a session key between the two parties. The actual data is then encrypted symmetrically under this session key. TLS, SSH, and disk encryption all use this hybrid arrangement.

Table 13.4: Comparison of symmetric and asymmetric encryption.
SymmetricAsymmetric (public-key)
KeySingle, sharedPublic + private pair
SpeedVery fast (AES-NI)100–1000 times slower
UseBulk dataKey exchange, signatures
ExampleAES, ChaCha20RSA, ECDH/X25519, Ed25519, ML-KEM

The last algorithm in the table is a response to a new threat. A sufficiently large quantum computer could solve both factoring and discrete logarithms quickly with Shor's algorithm. No such machine exists today. But traffic recorded today could be decrypted years from now, so the transition has already begun. In 2024 the US standards agency NIST published the lattice-based ML-KEM algorithm as a quantum-resistant key-establishment standard (FIPS 203).

13.2.5Hash functions

The third basic tool of cryptography is not encryption; it uses no key and cannot be reversed.

Definition 13.6

A cryptographic hash function produces a fixed-size output, the digest, from an input of any length, and has the following properties:

  • One-wayness: given a digest, finding an input that produces it is practically impossible.
  • Collision resistance: finding two different inputs that give the same digest is practically impossible.
  • Avalanche effect: changing a single bit of the input changes about half of the bits of the digest.

Today's standards are SHA-256 and SHA-3. SHA-256 produces a 256-bit digest, that is, 64 hexadecimal digits, from any input. To see the avalanche effect, let us compare the digests of two words.

Example 13.4

“MERHABA” and “MERHABa” differ only in the last letter. In ASCII, A (0x41) and a (0x61) differ in a single bit. The SHA-256 digests are:

MERHABA  cc44cc878588056ef8376b36fc7a2ba5124656c38597eb31291704e0af986112
MERHABa  57821b9db50b174af36bc659771a47e0eaa6aef8144b1a9e5b803c93e3280b18

There is no similarity between the two digests. Compared bit by bit, 124 of the 256 bits differ, which is very close to the expected half (128). The digests were computed with Python's hashlib library.

Hash functions appear in many places in an operating system. The digest of a downloaded file is compared with the published digest to see that the file was not corrupted. Passwords are stored not in the clear but as digests. Integrity-checking tools store digests of system files and find the ones that change. Git names every object by its digest.

Breaking a hash function means that finding collisions becomes practical. Collisions were produced in practice for MD5 in 2004 and for SHA-1 in 2017. Neither should be used for security purposes any more.

Common mistake

Treating a digest as compression, or as proof by itself. The input cannot be recovered from a digest, so it is not compression. An unsigned digest does not prove integrity either: an attacker who modifies the document can recompute and replace the digest that accompanies it. The digest must come over a trusted channel or be signed.

13.2.6Digital signatures

Public-key cryptography can also be used in the reverse direction. An operation performed with the private key can be checked by anyone with the public key, but only the owner of the private key can perform it. The digital signature builds on this observation.

Definition 13.7

A digital signature is the value obtained by processing the digest of a document with the sender's private key. Anyone can verify the signature with the sender's public key. A valid signature proves two things: the document has not changed (integrity) and it came from the owner of the private key (authenticity, non-repudiation).

Signing and verification proceed in the following steps (Figure 13.10).

  1. Digest. The sender, Alice, computes the digest of the document D: H(D). Signing the digest rather than the document itself is both fast and works on a fixed-size input.
  2. Signature. Alice signs the digest with her private key Priv_A and obtains the signature S. Today's algorithms are RSA-PSS, ECDSA, and Ed25519.
  3. Sending. The document, the signature, and the certificate carrying Alice's public key are sent together. If confidentiality is not wanted, the document is not encrypted.
  4. Verification. The receiver, Bob, recomputes the digest of the document himself and verifies the signature with Pub_A. If verification says that the signature was made over exactly this digest with Priv_A, the document is intact and came from Alice.
SenderReceiverDocument DSHA-256H(D)Sign (Priv_A)signature SDS+ certificate(Pub_A)SHA-256H(D) recomputedVerify (Pub_A)match
Figure 13.10: The flow of a digital signature: the sender signs the digest with her private key; the receiver recomputes the digest and verifies the signature with the public key.

What happens if a single byte of the document changes on the way? Bob computes the digest of the modified document D′. Because of the avalanche effect, this digest is completely different from H(D), and the signature does not match it (Figure 13.11). The attacker cannot produce a new valid signature either, because he does not have Priv_A.

SenderReceiverDocument DSHA-256H(D)Sign (Priv_A)signature SD'S+ certificate(Pub_A)SHA-256H(D) recomputedVerify (Pub_A)NO MATCH
Figure 13.11: If the document becomes D′ in transit, the recomputed digest does not match the signature and verification fails.
Example 13.5

Let us follow signing with the toy RSA key (n = 33, e = 3, d = 7). Let the digest of the document be h = 4.

  1. Bob signs with his private key: s = hd mod n = 47 mod 33 = 16.
  2. The receiver verifies with the public key: se mod n = 163 mod 33 = 4. The result equals the digest he computed himself; the signature is valid.
  3. An attacker modifies the document and the digest becomes 5. 163 mod 33 is still 4 and is not equal to 5; verification fails. To produce a signature matching the new digest one would need to know d = 7.

Signing is very easily confused with encryption. The two operations use the keys in opposite directions. In encryption, the sender uses the receiver's public key, and only the receiver can decrypt. In a signature, the sender uses her own private key, and anyone can verify. A message authentication code (MAC) produced with a shared secret key provides integrity but not non-repudiation: since the receiver also knows the key, the receiver could have produced the same code.

13.2.7Certificates and public-key infrastructure

Public-key cryptography leaves one question open. How does Bob know that the public key he holds really belongs to Alice? If Mallory distributes his own public key as “Alice's key,” he can read all messages sent to Alice. This is exactly the man-in-the-middle attack. The solution is a document, signed by a trusted third party, that binds the key to an identity.

Definition 13.8

A certificate (in the X.509 format) is a document that binds a public key to the identity of its owner, for example a domain name. It also contains a validity period and the signature of a certificate authority (CA) that vouches for the binding. The whole of the institutions and rules that produce, distribute, and revoke certificates is called a public key infrastructure (PKI).

Root CAself-signed; in the operating system/browsertrust storeIntermediate CAsigned by the rootwww.ornek.edu.trsigned by the intermediate CApublic key + domain namesignssignsBrowser verification1. Server certificate + intermediate CA arrive2. Signatures are verified along the chain3. Is the root in the trust store?4. Does the domain match? Expired?5. Revocation (OCSP/CRL) and CT log6. All OK → connection is trustedForged certificate (MITM)no trusted CA signed it, sono chain can be built → warning
Figure 13.12: The certificate chain: the root CA signs the intermediate CA, and the intermediate CA signs the server certificate. On the right, the browser's verification steps.

Certificates form a chain (Figure 13.12). At the head of the chain is the root CA. The root certificate is self-signed; nobody signs it. Trust in it comes from its being preinstalled in the trust store of the operating system or the browser. Root CAs keep their keys offline and leave the daily work to intermediate CAs. The server certificate signed by an intermediate CA binds, for example, the domain name www.ornek.edu.tr to the server's public key.

When a browser connects to an HTTPS site, it performs the following checks. The server sends its own certificate and the intermediate CA certificate. The browser verifies the signatures along the chain and checks that the chain reaches a root in its trust store. It checks that the domain name in the certificate matches the name being connected to and that the validity period has not expired. It checks whether the certificate has been revoked (via OCSP or CRL) and whether it appears in the publicly visible Certificate Transparency (CT) logs. If everything passes, the connection is considered trusted. Mallory's forged certificate, on the other hand, does not carry the signature of a trusted CA, so no chain can be built and the browser shows a warning.

The world of certificates has changed rapidly over the last decade. Let's Encrypt made obtaining certificates free and automatic through the ACME protocol; its certificates last 90 days. A short lifetime limits the damage of a stolen key and forces renewal to be automated. A joint body of browser vendors and CAs has decided to cut the lifetime of certificates gradually to 47 days by 2029.

13.2.8The TLS 1.3 handshake

All the earlier tools come together in a single protocol: TLS (Transport Layer Security). HTTPS, secure e-mail, and many other protocols run on top of TLS. The current version is TLS 1.3 (RFC 8446, 2018). The handshake at the start of a connection does three jobs together: it establishes a shared session key, it authenticates the server, and it confirms that the handshake has not been tampered with (Figure 13.13).

ClientServerClientHello: cipher suites, key_share (X25519 public value), randomServerHello: chosen suite, key_shareBoth sides compute the same secret with ECDHE → session keys{Certificate, CertificateVerify, Finished}{Finished} — client verified chain and signature{Application data} ⇄ AES-GCM / ChaCha20-Poly1305{ } = sent encrypted (green)
Figure 13.13: The TLS 1.3 handshake (simplified). Messages in curly braces are sent encrypted.
  1. ClientHello. The client sends the cipher suites it supports, a random value, and an ephemeral Diffie-Hellman public value. Today this value is mostly from the X25519 curve.
  2. ServerHello. The server chooses a cipher suite and sends its own Diffie-Hellman public value. Everything up to here goes in the clear.
  3. Shared secret. Each side computes the same shared secret from the other side's public value and its own secret value. This secret never travels over the network. The session keys are derived from it, and every message from now on is encrypted.
  4. The server's identity. The server sends its certificate. It then signs the digest of the handshake so far with its private key (CertificateVerify) and adds the Finished message. An attacker in the middle cannot produce this signature, because he does not have the server's private key.
  5. The client's confirmation. The client verifies the certificate chain and the signature. With its own Finished message it confirms that the handshake has not been modified. The whole procedure ends in a single round trip (1-RTT).
  6. Application data. Data now flows under symmetric authenticated encryption: AES-GCM or ChaCha20-Poly1305.

Ephemeral Diffie-Hellman values bring an important property: forward secrecy. The key of each session is derived from ephemeral values generated for that session, and these values are deleted when the session ends. The server's long-lived private key is used only for signing. Even if this key is stolen years later, the attacker's recorded old traffic cannot be decrypted.

13.2.9Code trace: the Diffie-Hellman key exchange

The Diffie-Hellman exchange at the heart of TLS can be traced by hand with small numbers. The two parties first agree on two public numbers: a prime p and a base g. Each party chooses a secret exponent, raises the base to it, and sends the result in the clear. Then it raises the other party's public value to its own secret exponent. Thanks to the commutativity of exponentiation, both parties arrive at the same number:

A = ga mod p,   B = gb mod p,   s = Ba = Ab = gab mod p

The code in the slides contains the modpow function, which computes large exponents efficiently, and the four computations of the exchange.

long modpow(long g, long e, long p) {
    long r = 1;
    while (e > 0) {
        if (e & 1) r = r * g % p;
        g = g * g % p;
        e >>= 1;
    }
    return r;
}
int main(void) {
    /* public: p = 23, g = 5 */
    long A  = modpow(5, 6, 23);
    long B  = modpow(5, 15, 23);
    long sA = modpow(B, 6, 23);
    long sB = modpow(A, 15, 23);
}

modpow uses the “square and multiply” method. The bits of the exponent e are scanned from right to left. In each round, if the bit is 1, the result r is multiplied by the current base g. Then the base is squared to bring it to the weight of the next bit: g, g2, g4, g8 … Because the result is reduced mod p after every multiplication, the numbers never grow. If the exponent has n bits, the loop runs n rounds. For 515, the naive method needs 14 multiplications, while this method finishes in 4 rounds. For 2048-bit exponents the difference is the difference between possible and impossible.

Alice has chosen the secret a = 6. The computation A = modpow(5, 6, 23) proceeds as in Table 13.5. The binary representation of 6 is 110.

Table 13.5: Trace of modpow(5, 6, 23). Initially r = 1, g = 5, e = 6. The values were recomputed with Python.
Rounde & 1rg (after)e (after)Explanation
1015 · 5 mod 23 = 23bit 0: r unchanged
211 · 2 = 22 · 2 = 41bit 1: r = r · g
312 · 4 = 84 · 4 = 160bit 2: r = r · g; the loop ends

The function returns 8: A = 8. This value is sent over the network in the clear; a = 6 never leaves Alice's machine. Bob runs the same function with his secret b = 15 (Table 13.6). The binary representation of 15 is 1111; since all four bits are 1, a multiplication happens in every round.

Table 13.6: Trace of modpow(5, 15, 23). Initially r = 1, g = 5, e = 15.
Rounde & 1rg (after)e (after)
111 · 5 = 525 mod 23 = 27
215 · 2 = 1043
3110 · 4 = 40 mod 23 = 17161
4117 · 16 = 272 mod 23 = 19256 mod 23 = 30

B = 19 travels over the network to Alice. Now each party raises the other's public value to its own secret exponent. Alice computes sA = modpow(19, 6, 23): the rounds pass through r = 1, 16, 2 and the result is 2. Bob computes sB = modpow(8, 15, 23): r = 8, 6, 12, 2, and the result is again 2. Both parties have computed 56·15 mod 23 = 590 mod 23.

Alicea = 6 (secret)s = 2Bobb = 15 (secret)s = 2network (everyone sees)p = 23, g = 5A = 8B = 19sB = modpow(8, 15, 23)Bob: A^b mod p = 8¹⁵ mod 23 = 2both sides found 5^(6·15) mod 23 = 2
Figure 13.14: The end of the exchange: Alice and Bob reach the shared secret s = 2; only p, g, A, and B crossed the network.

Eve, who listens to the network, sees p = 23, g = 5, A = 8, and B = 19. To find the shared secret she needs a or b. Finding a means solving the equation 5a mod 23 = 8. This is called the discrete logarithm problem. In this small example Eve tries 22 possibilities and finds a = 6 at once. In practice p is 2048 bits long, or the X25519 curve is used. No known algorithm can solve a problem of this size in reasonable time.

Common mistake

Believing that Diffie-Hellman alone prevents the man-in-the-middle attack. The exchange is secure only against an Eve who merely listens to the network. If Mallory steps in and performs one exchange with Alice and a separate one with Bob, she establishes a separate shared secret with each party and reads all the traffic. This is why in TLS the server signs the handshake with the key in its certificate. Unauthenticated Diffie-Hellman is not secure.

13.3Protection

Cryptography protects data outside the system, on the network or on disk. Inside the system a different question is asked: which objects can a running process access, and with which rights? This section presents the model for this question (the protection matrix), the two ways of implementing the model (access control lists and capabilities), and ways of reducing rights to a minimum.

13.3.1Protection domains

A computer system contains objects that need protection: files, memory segments, printers, semaphores, processes. Each object has operations of its own: a file is read, written, and executed; a printer is only written to. At a given moment, a process can access some of these objects with certain rights. The set of these (object, right) pairs is called a domain (Figure 13.15).

Definition 13.9

A protection domain is a set of (object, rights) pairs. Every process runs in some domain at every moment and can perform only the operations that domain permits.

Domain 1File1[R]File2[RW]Domain 2File3[R]File4[RWX]File5[RW]Domain 3File6[RWX]Plotter2[W]Printer1[W]Printer1 is in both D2 and D3: objects can be shared among domains
Figure 13.15: Three protection domains. Printer1 appears in both the second and the third domain: objects can be shared among domains.

In Figure 13.15, the first domain can read File1 and read and write File2. The second domain reads File3, uses all rights on File4, reads and writes File5, and writes to Printer1. The third domain has File6 (RWX), Plotter2 (W), and Printer1 (W) again. Domains need not be disjoint: the same object can appear in several domains, even with different rights.

In UNIX and Linux, a domain is determined by the set of a user ID (UID) and group IDs (GIDs). Two processes running with the same UID and GIDs access the same objects with the same rights. In addition, kernel mode and user mode are two separate domains. Code running in kernel mode can access all memory and all devices.

Processes can change domains while running. A system call moves the process from user mode to kernel mode; when the call ends, the process returns to its old domain. When a process executes a program with the setuid bit, it moves into the domain of the program's owner.

13.3.2The protection matrix

All the rights of all domains can be shown in a single table. This table, proposed by Lampson in 1971, is called the protection matrix or access matrix.

Definition 13.10

In the protection matrix (access matrix), each row stands for a domain and each column for an object. The cell at the intersection of row i and column j holds the rights that a process in domain i has over object j.

Table 13.7: A protection matrix in which domains also appear as objects. The “Enter” right permits moving into another domain.
File1File2File3File4File5Printer1File6Plotter2D1D2D3
D1RRWEnter
D2RRWXRWW
D3WRWXW

Table 13.7 adds an interesting feature to the matrix: domains are objects too. The Enter right in row D1, column D2 says that a process running in D1 may switch to D2. In this way, switching domains also comes under the control of the matrix. The same approach can model the rights to modify the matrix itself: copying a right to someone else, or editing rights as the owner of an object.

Every state of the matrix can be compared with the security policy. If the policy says that Eve must never be able to read a file, the cell for that file in Eve's row must never show R. If R appears in that cell after a sequence of legitimate commands, the system has gone from an authorized state to an unauthorized one. A natural question arises: given an initial state and the permitted commands, can we compute in advance whether an unauthorized state can be reached? In 1976 Harrison, Ruzzo, and Ullman showed that this question is undecidable in the general case. There is no algorithm that answers “can a right leak?” for every matrix. This result explains why models such as Bell-LaPadula and Biba, which restrict the rules from the start, were developed.

The practical problem with the matrix is its size. In a system with thousands of users and millions of files, the matrix has billions of cells, and the vast majority of them are empty. The matrix is very sparse. Even in the small example of Table 13.7, counting only the eight object columns, 15 of the 24 cells are empty. So the whole matrix is never stored. Either the columns or the rows are stored, and the empty cells are skipped.

13.3.3Two forms of the same matrix: ACLs and capabilities

Storing the matrix column by column means putting next to each object a list answering “who can access this object, and with which rights?” Storing it row by row means giving each domain a list answering “which objects can this domain access, and with which rights?” (Figure 13.16 and Figure 13.17).

Definition 13.11

An access control list (ACL) is a column of the matrix. It lists which domains can access an object and with which rights, and it is stored with the object. A capability list (C-list) is a row of the matrix: it lists the objects a domain can access and its rights over them. Each entry in the list is called a capability.

File1File2File3File4File5Printer1File6Plotter2D1RRWD2RRWXRWWD3WRWXWACL = column (stored with the object)File1D1:RFile2D1:RWFile4D2:RWXPrinter1D2:W → D3:WFile6D3:RWX
Figure 13.16: The non-empty columns of the matrix become ACLs. For example, the ACL of Printer1 is D2:W and D3:W.
File1File2File3File4File5Printer1File6Plotter2D1RRWD2RRWXRWWD3WRWXWCapability list = row (stored with the process/in the kernel)Process (D2)File3 : RFile4 : RWXFile5 : RWPrinter1 : WThe process presents the capability from the list when accessing an object; no name resolution or ACL scan needed
Figure 13.17: A row of the same matrix: the capability list of D2 is File3:R, File4:RWX, File5:RW, and Printer1:W.

In the ACL scheme, when a process wants to access an object, the kernel opens the object's ACL and looks for the process's identity in this list. In the capability scheme, the process presents the capability it holds when it accesses. It is enough for the kernel to check that the capability is valid; no name resolution or list scan is needed.

The two representations carry the same information, but make different questions easy to answer (Table 13.8).

Table 13.8: Comparison of ACLs and capability lists.
QuestionACL (column)Capability (row)
Where is it stored?Next to the objectWith the domain (in the process or in the kernel)
“Who can access this object?”Easy: look at the listHard: scan all processes
“What can this process access?”Hard: scan all objectsEasy: look at the list
Revoking a rightEasy: delete one entryHard: all copies must be found
Delegating a rightThe object's list must changeEasy: copy the capability
Cost at access timeList scanValidity check of the capability
Example 13.6

In the matrix of Table 13.7, we want to revoke D3's right to Printer1 immediately. In addition, D2 wants to delegate its read right on File5 to D1. In which representation is each job easy?

  1. Revocation. In the ACL scheme, Printer1's list is {D2:W, D3:W}; the D3 entry is deleted and the job is done. In the capability scheme, the capability in D3's list must be deleted. But D3 may have copied this capability to other processes earlier. To find all the copies, every capability list in the system must be scanned.
  2. Delegation. In the capability scheme, D2 hands D1 a copy of its File5:R capability; File5 itself is not touched. In the ACL scheme, a new D1:R entry must be added to File5's list; only the owner of the object can do this.

Real systems often combine the two representations. When opening a file, UNIX checks the permission bits, which are a kind of ACL. For the opened file it gives the process a file descriptor. This descriptor is in fact a capability: on the subsequent read and write calls the permission is not checked again. Even if the file's permissions are changed in the meantime, the open descriptor keeps working.

13.3.4UNIX permissions and POSIX ACLs

Classic UNIX uses a very compressed form of the ACL idea. Every file has an owner and a group. The file's i-node holds three bits for each of three classes: owner (u), group (g), and others (o). Each triple has read (r), write (w), and execute (x) bits. The nine bits in total are written as three digits in octal: r = 4, w = 2, x = 1.

$ ls -l report.txt
-rw-r----- 1 ali accounting 4096 report.txt
 rw-  owner   r--  group  ---  other

$ setfacl -m u:ayse:rw report.txt
$ getfacl report.txt
user::rw-
user:ayse:rw-
group::r--
mask::rw-
other::---

After the first character, the string -rw-r----- in the output splits into three triples. The owner ali can read and write (rw- = 4 + 2 = 6). Members of the group accounting can only read (r-- = 4). Others have no rights (--- = 0). The file's octal mode is 640, and it can be set with the command chmod 640 report.txt.

The permissions of newly created files are determined by the umask value. A program usually asks for 666 for a file and 777 for a directory. The kernel clears from this value the bits that are 1 in the umask. With the common umask 022, files get 644 (rw-r--r--) and directories 755 (rwxr-xr-x). With the stricter umask 077, files are open only to the owner: 600.

The nine-bit scheme is fast and fits in the i-node, but it is coarse-grained. If Ali wants to make his file writable not by the whole accounting group but only by Ayşe, nine bits are not enough. POSIX ACLs fill this gap. The command setfacl -m u:ayse:rw report.txt adds a named-user entry to the list. In the getfacl output we see this entry and a new line: mask. The mask limits the maximum rights that the named-user and group entries can reach. Even if Ayşe's entry is rw-, if the mask is set to r--, Ayşe can effectively only read. Files that carry an ACL are recognized in ls -l output by a + sign at the end of the permission string.

Example 13.7

A script file has mode 754. What can the owner, group members, and others do? What permissions do a new file and a new directory get when the umask is 027?

  1. 7 = 4 + 2 + 1: the owner reads, writes, and executes (rwx).
  2. 5 = 4 + 1: the group reads and executes (r-x).
  3. 4: others only read (r--). The string is rwxr-xr--.
  4. umask 027 clears write (2) from the group and everything (7) from others. File: 666 → 640 (rw-r-----). Directory: 777 → 750 (rwxr-x---).

The NTFS file system of Windows uses a richer ACL model. Each object's discretionary access control list (DACL) consists of ordered entries. Each entry carries a security identifier (SID), a rights mask, and a type, allow or deny. Explicit deny entries come before allows. The ACL of a folder passes to the files inside it through inheritance. On the command line, the icacls tool displays and edits these lists. The semantics of POSIX, NFSv4, and NTFS ACLs do not match exactly. For this reason, rights sometimes change in unexpected ways when files are moved between systems.

The advantage of the ACL scheme is that it is easy to understand. Who can access an object is visible at a glance, and a right is easily revoked per object. Its drawbacks are that administration gets harder in large systems and that the list is scanned on every access. The scanning cost is eased by caching: in UNIX, the permission check is made only at open time.

Example 13.8

Users are divided into four groups and an administrator role, and there are four objects (A, B, C, D) (Table 13.9). What is the ACL of object C? Which objects can Group 4 access?

Table 13.9: Protection matrix for groups and objects.
GroupABCD
Group 1RRWX——
Group 2W———
Group 3——XR
Group 4————
AdminRWXRWXRWXRWX

The ACL of C consists of the non-empty cells of its column: {Group 3: X, Admin: RWX}. Group 4's row is entirely empty, so it appears in no ACL. By the safe-default rule, this group cannot access any object.

13.3.5Code trace: an access control list

We can trace how a kernel scans an ACL with a small C function. The ACL of file A is column A of the protection matrix: Group 1 reads, Group 2 writes, and the administrator can do everything. Rights are encoded as bits: R = 4, W = 2, X = 1.

/* ACL of file A: R=4 W=2 X=1 */
struct entry { int group, rights; } acl[] =
    {{G1, 4}, {G2, 2}, {ADM, 7}};

int access(int group, int req) {
    for (int i = 0; i < 3; i++)
        if (acl[i].group == group) {
            int h = acl[i].rights;
            return (h & req) == req;
        }
    return 0;   /* not listed: denied */
}

The array has only three entries; the cells of Group 3 and Group 4 on A are empty, so they are not stored. The access function scans the list from the beginning. At the first entry that names the requesting group it decides and returns. The decision expression is (h & req) == req. If all the requested rights are present in the entry, the AND yields exactly the request. If even one is missing, the result differs and access is denied. If the group is not in the list, the loop completes and the function returns 0. Table 13.10 traces four calls.

Table 13.10: Four calls of the access function. The values were recomputed with Python.
Calli examinedMatching entryh & reqResult
access(G2, W)0, 1i = 1, h = 22 & 2 = 2allow
access(G1, W)0i = 0, h = 44 & 2 = 0 ≠ 2deny
access(G4, R)0, 1, 2none—deny (0)
access(ADM, R|X)0, 1, 2i = 2, h = 77 & 5 = 5allow
request: ADM · R|X (5)allowacl[] (stored with file A)G1 : R--i = 0G2 : -W-i = 1ADM : RWXi = 2
Figure 13.18: The last call: the administrator asks for read and execute together (5); a match is found at the third entry, and since 7 & 5 = 5, access is allowed.

The trace shows three lessons clearly. First, the decision is made at the first matching entry: Group 1's write request is denied and the list is not scanned any further. This is also why NTFS puts deny entries first. Second, for a request from a group that is not in the list, the whole list is scanned. This is the cost of every access with long ACLs: in a list of n entries, O(n) comparisons in the worst case. Third, the safe-default principle is built into the code. Everything not explicitly allowed is forbidden; the last line of the function says so.

Common mistake

Writing the decision expression as (h & req) != 0. This expression allows access if any one of the requested rights is present. If Group 1 asks for read and write together (6), the result is 4 & 6 = 4 ≠ 0, and access is allowed although the group has no write right. The correct expression requires all of the requested bits to be present in the entry.

13.3.6Capability lists

In the capability scheme, a capability is a ticket that gives its holder the right to access an object. The most important property of the ticket is that it cannot be forged. If a process could mint a “capability to write File7” on its own, the scheme would protect nothing. There are three ways to protect capabilities from forgery.

Keeping them in the kernel
The capability list lives in kernel memory. The process knows only the index of an entry in the list and passes this index to the system call: read(cap 2, …). UNIX file descriptors work exactly this way (Figure 13.19).
Tagged hardware
An extra bit is attached to every word in memory to show whether it is a capability. This bit can be changed only by special instructions. The CHERI architecture from the University of Cambridge brings this approach to current processors.
Cryptographic protection
The capability stays in the user's hands but carries a check field. This field is obtained by passing the object and the rights, together with a secret value known only to the server, through a one-way function (for example HMAC). If the user changes the rights, the check field no longer matches. The Amoeba distributed operating system used this method.
Processuser modesees only the index:read(cap 2, …)C-list in the kernel0File3 R1File4 RWX2File5 RW3Printer1 WCryptographically protected capabilityServerObjectRightsf(Object, Rights, Secret)Cannot be forged even if the user holds it:f is one-way (e.g. HMAC); the secret valueis known only to the server (Amoeba).
Figure 13.19: On the left, the C-list kept in the kernel: the process sees only an index. On the right, the cryptographically protected capability format.

Four basic operations are defined on capabilities. Copying a capability creates a new capability for the same object; this is delegation. Copying an object creates a new object and a new capability for it. Removing a capability deletes an entry from the list; the object stays in place. Destroying an object permanently deletes the object and its capability.

Pure capability systems live today in research and in specialized niches: the formally verified seL4 microkernel and Google's Fuchsia work through capabilities from top to bottom. FreeBSD's Capsicum framework, on the other hand, adds a capability mode to an ordinary UNIX. A process that enters this mode can no longer open new files by name; it can only use the descriptors it already holds.

13.3.7Least privilege and setuid

The famous 1975 paper by Saltzer and Schroeder lists the principles of secure system design. The best known of them is the following.

Definition 13.12

The principle of least privilege: every component should run with the smallest set of rights that suffices for its job, and should hold those rights only for as long as they are needed. If the component is compromised, the harm it can do is limited to this set.

UNIX has a classic situation that conflicts with this principle. The digests of passwords are in the file /etc/shadow. The file is owned by root and its mode is -rw-r-----: ordinary users cannot even read it. So how does Ali change his own password? The solution is the setuid bit. The program /usr/bin/passwd is owned by root and shows an s instead of x in its permissions: -rwsr-xr-x. When this bit is set, the program runs with the rights of the file's owner, not of the person who runs it.

To understand this behavior, one must know the three user IDs of a process. The real ID (ruid) is the user who started the process. The effective ID (euid) is the ID used in permission checks. The saved ID (suid) stores an ID the process may return to later. Normally all three are equal. When a program with the setuid bit is started by execve, the effective and saved IDs are changed to the file's owner; the real ID does not change.

/* /usr/bin/passwd  -rwsr-xr-x root */
int main(void) {
    uid_t me = getuid();
    int fd = open("/etc/shadow", O_RDWR);
    update_own_entry(fd, me);
    close(fd);
    setresuid(me, me, me);
    /* ... rest of the work ... */
    fd = open("/etc/shadow", O_RDWR);
    if (fd < 0) perror("open");
    else close(fd);
    return 0;
}

The code is a sketch of a passwd that uses its privilege only as long as necessary. getuid() returns the real ID. From it the program learns on whose behalf it runs and changes only that user's line. In the open call the kernel checks access against the effective ID. Since euid is 0, the file opens. As soon as the job is done, setresuid(me, me, me) sets all three IDs to 1000. Because the saved ID changes too, there is no way back. The second open at the end now fails with EACCES and returns −1; the program checks the return value, and perror prints the error as “open: Permission denied” (Table 13.11).

Table 13.11: Tracing the IDs when Ali (uid 1000) runs passwd. The values were verified with a Python simulation.
StepruideuidsuidResult
shell (ali)100010001000unprivileged
execve (setuid root)100000effective ID becomes the file owner
getuid()100000returns 1000
open("/etc/shadow")100000allowed (euid 0)
setresuid(1000, 1000, 1000)100010001000privilege dropped permanently
open("/etc/shadow")100010001000EACCES, fd = −1
passwd processruid = 1000 (ali)euid = 1000/etc/shadow-rw-r-----root shadowEACCES: permission denied
Figure 13.20: After the privilege is dropped, euid is 1000 and access to /etc/shadow is denied.

The value of dropping privilege this early shows when a bug appears in the rest of the program. Suppose the later part of the program has a buffer overflow and an attacker exploits it to run his own code. If the privilege had not been dropped, the attacker's code would run as root. Because it was dropped, it runs with Ali's rights and can do no more than Ali could already do. This is why setuid-root programs are the classic target of privilege-escalation attacks. Each must be examined carefully, and their number should be kept to a minimum.

Common mistake

Thinking that seteuid(getuid()) drops the privilege. This call changes only the effective ID; the saved ID stays 0. Because an unprivileged process can set its effective ID to its real or saved ID, the attacker's code becomes root again with seteuid(0). To drop permanently, the saved ID must be changed too: setresuid(me, me, me).

13.3.8Linux capabilities and design principles

In traditional UNIX, root can either do everything or nothing. Ports below 1024 are privileged. So a web server that wants to listen on port 80 has to be root. The web server thereby also gains, needlessly, the rights to bypass file permissions, change the clock, and load kernel modules. Linux splits root's single block of authority into about 41 separate pieces and calls them capabilities (Figure 13.21). The word “capability” here is not the same as in the capability-list scheme; it means “a piece of privilege.”

root (uid 0)allowed everythingCAP_NET_BIND_SERVICEports below 1024CAP_NET_ADMINnetwork configurationCAP_SYS_TIMEsetting the clockCAP_DAC_OVERRIDEbypassing file permissionsCAP_KILLsignaling othersCAP_SYS_ADMIN“the new root”: very broad≈ 41 capabilities; each thread has permitted, effective, inheritable, and bounding sets
Figure 13.21: The division of root's authority into Linux capabilities. CAP_SYS_ADMIN is so broad that it is called “the new root.”

For example, CAP_NET_BIND_SERVICE is the right to open ports below 1024. CAP_DAC_OVERRIDE bypasses file permissions, CAP_KILL sends signals to processes of other users, and CAP_SYS_TIME sets the system clock. Every thread has four capability sets: permitted, effective, inheritable, and bounding. A capability can also be assigned to a file. The commands below give the web server only the right to open low-numbered ports.

$ sudo setcap cap_net_bind_service=+ep /usr/local/bin/websrv
$ getcap /usr/local/bin/websrv
/usr/local/bin/websrv cap_net_bind_service=ep     # may bind port 80, no other root rights

The suffix =ep says that the capability is added to the permitted (p) and effective (e) sets. The program can now listen on port 80 without being root. Even if it is compromised, it cannot bypass file permissions or kill other processes.

The list by Saltzer and Schroeder does not end with least privilege. The other principles find counterparts in today's systems as well.

Fail-safe defaults
Everything not explicitly allowed is forbidden. The return 0 on the last line of the ACL scan is this principle.
Complete mediation
Every access is checked; a permission once granted is not treated as valid forever in a cache. This is the first condition of the reference monitor.
Open design
Security does not depend on the design being kept secret. This is the general form of Kerckhoffs's principle.
Separation of privilege
A critical operation is made to depend on more than one condition or person. A safe with two keys and approval by two people are examples of this principle.
Psychological acceptability
A security mechanism must not exasperate the user. Otherwise users find ways to get around it: they paste the password on the screen, they set permissions to 777.

Today's software applies these principles through privilege separation. The OpenSSH server is a good example. A small root process does only the jobs that need privilege, such as authentication. Risky jobs, such as parsing data that arrives from the network, run in a child process with no privileges at all. systemd likewise limits which capabilities a service may use with CapabilityBoundingSet= in service files. NoNewPrivileges= prevents a service from gaining new privileges through setuid programs.

13.4Formal security models

The protection matrix can express any policy, but whether a right can leak cannot be computed in the general case. Formal models solve this problem by restricting the rules from the start. The rules are so simple that, as long as they are obeyed, a particular harm can be proved impossible. This section covers two classic models and a leakage path that even they cannot close: covert channels.

In both models it is the system, not the user, that does the enforcing. With ordinary UNIX permissions the owner of a file can change the permissions as he likes; this is called discretionary access control (DAC). In formal models, the policy is set by the administrator and no process can loosen it; this is called mandatory access control (MAC).

13.4.1The Bell-LaPadula model

In military organizations, documents are divided into classification levels. In the arrangement used in the slides, these levels from highest to lowest are Top Secret (4), Secret (3), Confidential (2), and Unclassified (1). Every person also has a clearance level. The model defined by Bell and LaPadula in 1973 is the computer counterpart of this arrangement. It has a single goal: to prevent information from leaking from a high level to a low level.

Definition 13.13

In the Bell-LaPadula model (BLP), every process and every object carries a confidentiality level. The model imposes two rules:

  • Simple security property: a process at level k may read only objects whose level is less than or equal to k (no read up).
  • * property (star property): a process at level k may write only to objects whose level is greater than or equal to k (no write down).

The first rule agrees with intuition: a person cleared for Secret cannot read a Top Secret document. The second rule looks odd at first sight. Why should a process at the Secret level not be able to write to an Unclassified file? The answer is that a process can carry the information it reads to where it writes. If a process that reads a Secret document copies its contents into an Unclassified file, the information has leaked downward. Writing up, on the other hand, does not break confidentiality: if Secret information moves into a Top Secret file, it is protected more tightly. This kind of write is usually a “blind” append; the process cannot read the file it writes.

Top Secret (4)objectSecret (3)objectProcessConfidential (2)objectUnclassified (1)objectread ✗
Figure 13.22: No read up: a process at the Secret level cannot read a Top Secret object.
Top Secret (4)objectSecret (3)objectProcessConfidential (2)objectUnclassified (1)objectwrite ✗Even if a Trojan horse runs inside the Secret process, it cannot write information down
Figure 13.23: No write down: even a Trojan horse inside the process cannot write information to the Unclassified level.
Example 13.9

A process running at the Secret (3) level makes read and write requests to objects at the four levels. Which ones does BLP allow?

  1. Reading. The object level must be ≤ 3. Top Secret (4): denied. Secret, Confidential, Unclassified: allowed.
  2. Writing. The object level must be ≥ 3. Top Secret and Secret: allowed. Confidential and Unclassified: denied.

The process both reads and writes at its own level. It only reads below and only writes above.

The real gain of BLP is that its rules do not depend on the good will of the user. Suppose a user cleared for Secret runs a program with a Trojan horse hidden inside it. The program runs with the user's rights and can read Secret documents. Under DAC the program could write what it read into a publicly readable file. Under BLP this write is a write down, so the system denies it. The rule works regardless of what the program is trying to do.

13.4.2The Biba model

BLP protects only confidentiality; it says nothing about integrity. An Unclassified process may write to a Top Secret file and corrupt it. In 1977 Biba proposed a model that protects integrity. Biba is the mirror image of BLP: this time the levels show not confidentiality but trustworthiness. In the example in the slides the levels are High (system), Medium (user), and Low (Internet).

Definition 13.14

In the Biba model, every process and object carries an integrity level. The model imposes two rules:

  • Simple integrity property: a process at level k may read only objects whose level is greater than or equal to k (no read down).
  • * integrity property: a process at level k may write only to objects whose level is less than or equal to k (no write up).

The meaning of the no-write-up rule is clear: user processes cannot modify system files. The no-read-down rule is subtler. A process that reads untrusted data from the Internet and acts on it becomes “tainted.” Malicious input can change the behavior of the process, and the process can then use this behavior to write to more trusted objects. Biba stops this at the source.

High (system) (3)objectMedium (user) (2)objectLow (Internet) (1)objectProcesswrite ✗A browser process with low integrity cannot write to user files
Figure 13.24: No write up in Biba: a browser process with Low integrity cannot write to the user files at the Medium level.

A real application of Biba is Windows's Mandatory Integrity Control (MIC). In Windows, processes and objects carry one of the integrity levels Low, Medium, High, and System. Ordinary applications run at the Medium level. The tab processes of browsers run at the Low level. Even if an exploit in a web page takes over the browser process, it cannot write to the user's documents at the Medium level. This is exactly the no-write-up rule.

13.4.3Comparing the two models

The two models use the same structure in opposite directions (Table 13.12).

Table 13.12: Bell-LaPadula and Biba.
Bell-LaPadula (1973)Biba (1977)
ProtectsConfidentialityIntegrity
ReadingDown free, up forbiddenUp free, down forbidden
WritingUp free, down forbiddenDown free, up forbidden
PreventsInformation leaking downwardTainted data spreading upward
TodaySELinux MLS, military systemsWindows MIC, FreeBSD and Linux integrity policies
Bell-LaPadula (confidentiality)Top SecretprocessConfidentialreadscannot readwritescannot writeBiba (integrity)HighprocessLowreadscannot readwritescannot write
Figure 13.25: The directions in which a process can read and write under the two models. Instead of memorizing the arrows, remember what each model prevents.
Example 13.10

A process is at the Medium level. What do the two models say about the requests to read High, write High, read Low, and write Low? If both are applied together, what can the process access?

Table 13.13: Four requests by a Medium-level process. The decisions were verified with Python.
RequestBLP (confidentiality)Biba (integrity)
Read High (read up)denyallow
Write High (write up)allowdeny
Read Low (read down)allowdeny
Write Low (write down)denyallow

In every row, one of the models denies. If both models are applied together, the process can read and write only objects at its own level. One protects confidentiality, the other integrity, and their goals conflict.

The names are easy to confuse. In BLP, the simple security property forbids reading up and the * property forbids writing down. In Biba, the simple integrity property forbids reading down and the * integrity property forbids writing up. In both models the word “simple” marks the read rule and the star marks the write rule.

Common mistake

Remembering the BLP rules as “no write up.” In confidentiality the danger is information flowing down; the write that is forbidden is the one that goes downward. The way to derive the rule is this: first ask what the model wants to protect, then think about which direction of information flow would break that goal.

The two models share a limitation: they control only explicit read and write operations. Information can be transferred without being written to a file. The next topic deals with these paths.

13.4.4Covert channels and steganography

In 1973 Lampson asked a question: can a program be confined completely, so that it does not leak the secret information it processes while providing its service? This is called the confinement problem. The scenario is as follows: a client gives a server its secret data to process. The server is malicious and wants to pass the data on to an accomplice outside. The operating system confines the server: it cannot write files, cannot connect to the network, and cannot exchange messages with the accomplice. Lampson's answer is negative.

Definition 13.15

A covert channel is a way of transferring information that the system designer did not intend for communication and that bypasses the security policy.

ClientconfinedServerprocesses secret dataAccomplicesecret dataopen channel ✗covert channel ✓Steganography181…1114…073…1209…190…037…1last bit = hidden message
Figure 13.26: The confined server's open channel is closed, but it can leak data to the accomplice through a covert channel. On the right, steganography: a message hidden in the last bits of pixels.

Every shared resource can be a covert channel. Channels fall into three kinds.

Storage channel
Information is transferred by a change in a shared state: whether a file exists, whether it is locked or open, how full the disk is.
Timing channel
Information is transferred by the timing of events. If the server uses the CPU heavily it sends 1, if it stays idle it sends 0. The accomplice reads the bits by measuring how much its own work slows down. Cache latency is such a channel too.
Resource channel
Information is transferred by how much of a shared resource is used: the page-fault rate, the volume of network traffic.

Closing every covert channel is practically impossible, because the state of every resource that processes share can be observed by the other processes. What can be done is to reduce the channels' bandwidth, that is, the number of bits per second they can carry. Adding noise, separating resources by level, and reducing the resolution of clocks are among these methods.

A close relative of the covert channel is steganography: hiding the existence of information instead of encrypting it. In a color image, the red, green, and blue components of each pixel are eight bits each. Changing the least significant bit of each component changes the color by at most 1/256. The eye cannot see the difference. The last bits of the six values in Figure 13.26 are 1, 0, 1, 1, 0, 1 in order. At one bit per channel, a 1920 × 1080 photograph can store 777,600 bytes. In Tanenbaum's well-known example, five Shakespeare plays are hidden inside a photograph with three zebras; the image does not change at all to the eye.

13.4.5A covert channel through file locking

Let us build a concrete storage channel. The server and the accomplice agree in advance: in each time interval, if file F is locked, a 1 is considered sent; if it is free, a 0. To send a bit, the server locks or releases F. In the same interval the accomplice tries to lock F. If the attempt fails, the file is locked and the bit is 1; if it succeeds, the bit is 0. In this arrangement there is neither a read nor a write; the contents of F never change. No operation that BLP controls takes place, yet information flows.

ServerFile FAccomplicet1locklocked1t2unlockfree0t3locklocked1t4locklocked1t5unlockfree0t6unlockfree0t7locklocked1t8unlockfree0Received bits: 10110010
Figure 13.27: One byte over eight intervals: the accomplice reads the sequence 10110010 from its lock attempts.

In the timeline of Figure 13.27, over eight intervals the server switches F in the order lock, unlock, lock, lock, unlock, unlock, lock, unlock. The accomplice receives the sequence 10110010, that is, the value 0xB2 = 178. If the interval is 10 ms, there are 100 intervals per second, giving a channel of about 100 bit/s. A 256-bit encryption key leaks at this speed in 2.56 seconds.

Example 13.11

The server sends the value secret = 'K', starting from the most significant bit:

for (int i = 7; i >= 0; i--) {
    if ((secret >> i) & 1) lock(F);
    else                    unlock(F);
    sleep_ms(10);
}
  1. The ASCII code of 'K' is 0x4B; in binary 01001011.
  2. From i = 7 down to 0 the bits are 0, 1, 0, 0, 1, 0, 1, 1. The server does unlock, lock, unlock, unlock, lock, unlock, lock, lock in turn.
  3. In each interval the accomplice computes bit = try_lock(F) ? 0 : 1 and after 80 ms obtains 01001011 = 0x4B = 'K'.

An administrator who finds the channel can lengthen the interval or add random delays to the lock state. These measures reduce the speed of the channel, but do not bring it to zero.

13.5Authentication

All the decisions of the protection matrix rest on knowing which user a process belongs to. This is established when the user identifies himself as the system starts. If authentication is weak, even the best access control is useless: the attacker walks in under the identity of a legitimate user and uses all of that user's rights.

13.5.1Authentication factors

Definition 13.16

Authentication means verifying that a user is who he claims to be. Deciding which operations will be permitted is a separate step, called authorization.

Authentication can rely on four kinds of evidence, that is, factors.

Something you know
A password, a PIN, a security question. It is cheap and usable everywhere. But it can be stolen or guessed, and users reuse the same password on many sites.
Something you have
A phone, a smart card, a FIDO2 security key, a TOTP generator. It can be stolen physically, but it cannot be copied remotely.
Something you are
A fingerprint, a face, an iris. It is easy to use, but it cannot be changed: if it leaks, it is permanently “burned.”
Where you are or how you behave
Location, IP address, typing rhythm, device fingerprint. Usually used not alone but as an additional risk signal.

Multi-factor authentication (MFA) means asking for at least two factors from different categories together. The category condition matters. “Password + security question” is not MFA, because both are something you know, and the same phishing page can collect both at once. MFA is by itself the most effective measure against stolen passwords.

Older systems used a kind of challenge-response verification. The user was asked questions at registration, and one of them was chosen at random at login. Typical questions were the mother's maiden name or the name of the first pet. Because most of these answers can be found easily on social media today, the method is considered weak. The strong form of the challenge-response idea is cryptographic: the server sends a random number, and the user's device processes it with a secret key. FIDO2 uses this idea.

13.5.2Password storage: salt and slow hashing

Passwords are never stored in the clear. If they were, an attacker who got hold of the password file, or an administrator who could read the file, would learn all the passwords at once. Since users use the same password elsewhere, the harm would not stay limited to one system. The system stores the digest of the password instead. At login, the digest of the password the user typed is computed and compared with the stored one.

But a plain digest is not enough (Figure 13.28). People often choose the same passwords. Since the same password gives the same digest, an attacker looking at the digest file immediately sees which users chose the same password. Worse, the attacker can compute the digests of millions of common passwords once in advance and put them into a table. Such tables are called rainbow tables. Every digest in a leaked file is looked up in this table, and thousands of passwords are cracked in one pass.

PasswordSaltSlow hash Hali7Gx!veli7Gx!cankQ4zThe same password wouldgive the same digest: the attackersees the repetition and cracks itwith a precomputed table
Figure 13.28: With unsalted digests, ali and veli have the same password and so the same digest; the attacker sees the repetition.
Definition 13.17

A salt is a random value generated separately for each user and added to the password before hashing. The salt is not secret; it is stored in the clear next to the digest.

The effect of the salt is simple: the same password is now a different input. Even if ali and veli have the same password, their digests are completely different because their salts differ. Precomputed tables are useless too, because a separate table would be needed for every possible salt. Even 1970s UNIX used a 2-character, that is 12-bit, salt. This meant each password could be stored in 4096 different ways and that the table size would grow 4096-fold.

A salt alone is not enough. General-purpose hash functions such as SHA-256 are designed to be fast. A current graphics card can compute billions of SHA-256 hashes per second. In password storage the opposite is wanted: each guess should be expensive. For this reason passwords are hashed with deliberately slow, memory-hungry functions. The current recommendation is Argon2id (RFC 9106); scrypt and bcrypt are also used. One verification takes a few milliseconds and the user does not notice. Billions of guesses, however, take years.

# Registration / password change
salt = os.urandom(16)
h = argon2(password, salt)
store(user, salt, h)

# Login attempt
salt, h = lookup(user)
g = argon2(attempt, salt)
if constant_eq(g, h): ok()

The pseudocode in the slides shows two operations. At registration or password change, a 16-byte random salt is generated. The password is passed through Argon2 with this salt, and the user name, salt, and digest are stored together. At login, the user's salt and digest are looked up, the attempt is hashed with the same salt, and the two digests are compared.

Doing the comparison with constant_eq is not a detail. An ordinary comparison stops at the first differing byte. If the attacker can measure the response time very precisely, he can deduce from the time how many leading bytes are correct. A constant-time comparison always compares all the bytes and prevents this timing leak.

PasswordSaltSlow hash Hali7Gx!a3f1+b91c4e…veli7Gx!9b2e+2f87aa…cankQ4z5d7c+d013f5…Stored: salt + H.Argon2 is deliberately slowand memory-hard: brute forcewith GPU/ASIC is expensive
Figure 13.29: Each user has a separate salt; the same password gives different digests. What is stored is the salt and the slow digest.
Common mistake

Thinking that the salt must be kept secret, or that a salt makes weak passwords safe. The salt prevents only mass attacks and precomputation. If the attacker targets a single user, he knows that user's salt and tries dictionary passwords one by one. Against a weak password, a slow hash and a long password help. After a leak, passwords must be reset in every case.

13.5.3Brute-force time

It is instructive to see the separate contributions of the salt and of slowness in numbers.

Example 13.12

Passwords consist of 8 lowercase letters (a 26-letter alphabet). The attacker wants to crack the digest of a single user in a leaked database. How long does it take in the worst case?

  1. Number of possible passwords. There are 26 choices for each position: 268 = 208,827,064,576 ≈ 2.09 × 1011.
  2. Plain SHA-256. At 1010 guesses per second: 2.09 × 1011 / 1010 ≈ 21 seconds.
  3. Argon2id. Since each guess is expensive, let only 104 guesses per second be possible: 2.09 × 1011 / 104 ≈ 2.09 × 107 seconds ≈ 242 days. The slow hash has made each guess 106 times more expensive.
  4. A longer password. With 10 characters and 62 symbols (uppercase, lowercase, and digits), the space becomes 6210 ≈ 8.4 × 1017. Even with plain SHA-256 this takes about 2.66 years, and with Argon2id about 2.66 million years.

All values were computed with Python.

Where is the salt in this calculation? The salt does not change the time for a single user. The effect of the salt shows up when the attacker wants to crack all the users. In the unsalted arrangement, the attacker computes the digest of each candidate once and compares it with the digests of a million users at the same time: the work is the same as for a single user. In the salted arrangement he has to start over for each user. With a million users and plain SHA-256, the 21-second job grows to 106 × 21 seconds, about 242 days. The salt multiplies the work by the number of users; slowness raises the price of each guess. Neither can replace the other.

13.5.4MFA and TOTP

The most common second factor added next to the password is the phone. The phone either receives a code from the server or generates the code itself (Figure 13.30).

Servershared secret KAppsame secret KTOTP = HMAC(K, time / 30 s)KclockHMAC739 412renewed every 30 sThe code does not carry the secret K over the network; it cannot be reused (valid only for those 30 s)
Figure 13.30: TOTP: the server and the app know the same secret K and the same time; the code is derived from HMAC(K, time / 30 s).
SMS code
Common but weak. The attacker can trick the carrier into moving the number to his own SIM card (SIM swapping) or redirect messages through weaknesses in the SS7 protocol of the phone network. It is still better than having no second factor at all.
TOTP generator app
Time-based one-time password (TOTP, RFC 6238). At registration the server and the app share a secret key, usually through a QR code. From this key and the clock, the app generates a new code every 30 seconds. It works offline. But it is open to phishing: the user can type the code into a fake site as well.
Push notification approval
The user taps a login approval notification on the phone. It is easy, but vulnerable to approval fatigue attacks: the attacker sends dozens of requests in a row and the user finally gets tired and approves one. For this reason number matching is added, in which the user types a number shown on the screen into the phone.

Note that a TOTP code does not carry the secret key over the network. The code is a one-way function of the key and the time. Even if an attacker sees a code, he cannot recover the key from it. The code is also valid only within its own 30-second window.

13.5.5Code trace: generating a TOTP code

How the phone and the server produce the same code can be seen in the C function in the slides. The trace uses the test key of RFC 6238: the 20 bytes of the ASCII string “12345678901234567890”.

uint32_t totp(uint8_t *K, uint64_t t) {
    uint64_t T = t / 30;    /* 30 s */
    uint8_t h[20];
    hmac_sha1(K, T, h);
    int o = h[19] & 0x0F;   /* offset */
    uint32_t v = (h[o] & 0x7F) << 24
               | h[o+1] << 16
               | h[o+2] << 8
               | h[o+3];
    return v % 1000000;     /* 6 digits */
}

The function works in four steps.

  1. Time step. The Unix time t (seconds since 1970) is divided by 30: T = t / 30. Because this is integer division, every moment in the same 30-second window gives the same T. Seconds 0–29 fall into T = 0, seconds 30–59 into T = 1, and seconds 60–89 into T = 2. For t = 59, T = 1.
  2. HMAC. T, as an 8-byte big-endian number, is passed through HMAC-SHA1 together with K. The result is a 20-byte digest: 75 a4 8a 19 d4 cb e1 00 64 4e 8a c1 39 7e ea 74 7a 2d 33 ab. Someone who does not know K cannot produce this value.
  3. Dynamic truncation. 4 of the 20 bytes must be chosen. The digest itself determines where: the low half of the last byte is the offset. h[19] = 0xab; 0xab & 0x0F = 0xb = 11. So o = 11.
  4. The code. The bytes h[11] … h[14], that is c1 39 7e ea, are combined into a 32-bit number. The top bit of the first byte is cleared with & 0x7F (0xc1 → 0x41). The reason is to keep the number from coming out negative on systems where it is interpreted as signed. v = 0x41397eea = 1094287082. The last six digits are v mod 1,000,000 = 287082.
750a418a2193d44cb5e160076484e98a10c11139127e13ea1474157a162d173318ab19h[11..14] = c1 39 7e eatop bit cleared → v = 1094287082
Figure 13.31: h[19] = 0xab selects the offset 11; h[11..14] = c1 39 7e ea, and with the top bit cleared, v = 1094287082.

The phone shows 287082; the server makes the same computation and compares it with the value the user typed. After 30 seconds, everything changes (Table 13.14). At t = 75, T = 2. A T that is larger by just one gives a completely different digest. This time the last byte is 0x44, the offset is 4, and the code is 359152.

Table 13.14: The TOTP computation at two moments. The values were recomputed with Python's hmac library; the 8-digit result (94287082) is the same as the test vector of RFC 6238.
tTh[19]oh[o..o+3]vCode
5910xab11c1 39 7e ea1094287082287082
7520x44408 2f ef 30137359152359152

The phone's clock can drift a few seconds from the server's. Servers therefore usually accept the codes of the previous and the next step as well: T − 1, T, and T + 1. This means that a code is valid over a window of about 90 seconds. The probability of hitting the right code by random guessing is 3 / 106 per attempt. As long as the server limits the number of attempts, this probability is negligible.

Example 13.13

What is T at t = 1,700,000,000? Over what interval is the same code valid? If the server accepts T − 1 … T + 1, over what interval could a code entered right now have been generated?

  1. 1,700,000,000 / 30 = 56,666,666.67; the integer part gives T = 56,666,666.
  2. The window starts at T · 30 = 1,699,999,980 and lasts 30 seconds: 1,699,999,980 … 1,700,000,009.
  3. The start of T − 1 is 1,699,999,950 and the end of T + 1 is 1,700,000,039. The accepted window is 90 seconds.

13.5.6FIDO2, WebAuthn, and passkeys

TOTP is strong against password theft, but weak against phishing. The user types both the password and the current code into a fake login page. The attacker relays these two to the real site within a few seconds and gets in while the code is still valid. The root of the problem is that no mechanism checks which site the user is giving the code to. FIDO2 and its web interface WebAuthn close this hole (Figure 13.32).

BrowserSecurity keythe private key stays hereServerrandom challengeorigin-bound signaturesigned response (with private key)verifies the signaturewith the public keyThe signature includes the site's origin: a response given to a fake site is invalid at the real site → cannot be phished
Figure 13.32: FIDO2: the security key signs the server's random challenge, bound to the origin of the site; the server verifies the signature with the public key.

The scheme rests on public-key cryptography. When the user registers with a site, the device generates a new key pair for that site. The private key never leaves the device's secure hardware, that is, the TPM, the Secure Enclave, or the USB security key. Only the public key is sent to the server. At login the server sends a random challenge. The browser adds to this challenge the origin of the site it is connected to, that is, the triple of protocol, domain name, and port. The device signs the two with the private key, and the server verifies the signature with the stored public key.

The resistance to phishing comes from this origin. If the user visits a fake site such as example-login.com, the browser puts that fake origin into the signature. Moreover, the device finds no registered key for the fake site. Even if the attacker relays the response to the real site, the signature is invalid because the origin does not match. The user's carelessness does not change the outcome; the browser does the checking.

The other gains of the scheme matter too. The server stores only public keys; even if the database leaks, nobody can log in with these keys. There is no shared secret, and the same key is never reused on another site, because a separate pair is generated for each site. Passkeys are the form of FIDO2 credentials that can be synchronized securely across a user's devices. They are designed to replace passwords.

13.5.7Biometric authentication

Biometrics measures a physical or behavioral characteristic of a person: fingerprint, face, iris, voice. At first sight it looks ideal: it cannot be forgotten, lost, or handed over. But every measurement is slightly different, and the system compares the measured value with the enrolled template against a threshold. So there are two kinds of error (Table 13.15).

Table 13.15: Measures of biometric systems.
MeasureDescription
False acceptance rate (FAR)Rate of accepting a stranger: a security risk
False rejection rate (FRR)Rate of rejecting the real user: a usability problem
Liveness testCheck against a photograph, a mask, or a fingerprint mold
IrrevocabilityIf a fingerprint leaks it cannot be changed; a password can

FAR and FRR are linked. If the threshold is tightened, fewer strangers are accepted, but the real user is rejected more often. If it is loosened, the opposite happens. Even a small FAR matters at large numbers. In a system with a FAR of 1/100,000, the probability that at least one of a thousand different strangers' attempts is accepted is 1 − (1 − 10−5)1000 ≈ 1%.

The fundamental limit of biometrics is this: it is good for an identity but bad for a secret. Faces and fingerprints are not secret; people leave fingerprints on the surfaces they touch every day and photographs on social media. The right use is therefore local. Biometrics works as a factor that unlocks secure hardware inside the device; for example, Face ID opens access to the keys in the Secure Enclave. The raw template never leaves the device. Alone it is not suitable for remote authentication, and it is usually combined with a device in the user's hand. The first devices that measured finger length are historical today. Today's systems use the minutiae of fingerprint ridges, the three-dimensional shape of the face, and the iris pattern. A hardware-backed liveness test is also essential.

13.5.8How do attackers get into a system?

The weak points of authentication are the entry paths that attackers use most often (Table 13.16).

Table 13.16: Common initial-access paths and countermeasures.
PathDescriptionCountermeasure
PhishingCollecting passwords with a fake login pageFIDO2, user training
Credential stuffingTrying leaked passwords on other sitesUnique passwords, MFA
Brute force / dictionaryGuessing a weak passwordSlow hashing, rate limiting, lockout
Unpatched vulnerabilityExploiting a known vulnerabilityFast patch management
Social engineeringTricking the help deskProcess and verification
Default or weak credentialsadmin/admin, a port left openHardening

A real attack is seldom a single step; it is usually a chain (Figure 13.33). The attacker first obtains initial access through phishing or a vulnerability. This access is usually an ordinary user account. Then, with a local vulnerability, he performs privilege escalation and becomes root. Next he spreads to other machines on the same network by lateral movement. Finally he achieves persistence by installing a backdoor or a rootkit: he stays inside even if the machine is rebooted.

1 · Initial accessphishing, vulnerability2 · Privilege escalationlocal vulnerability → root3 · Lateral movementother machines4 · Persistenceback door, rootkitMFA and FIDO2 · patching and least privilege · network segmentation · EDR and secure boot: a defense at every link
Figure 13.33: The attack chain and the defense at each link: MFA and FIDO2, patching and least privilege, network segmentation, EDR and secure boot.

The chain view shows once again that the defense must be layered as well. MFA makes initial access harder. Patching and least privilege block escalation. Network segmentation stops lateral movement. Endpoint monitoring and secure boot catch persistence. The failure of a single link must not lead to the takeover of the whole system.

13.6Software vulnerabilities

Even if authentication and access control were perfect, bugs in programs would open new doors for attackers. A bug becomes a security vulnerability when it makes the program do something its designer never foresaw. The most dangerous are memory errors that let the attacker run code of his own choosing. This section covers the most classic of them, the stack buffer overflow, the defenses developed against it, and TOCTOU, a race-condition vulnerability.

13.6.1Stack buffer overflow

When a function is called in C, a frame is opened for it on the stack. The frame holds the function's local variables, the caller's saved frame pointer, and the return address. The return address is where the processor will continue executing when the function ends. On the x86 family the stack grows from high addresses to low addresses. So the return address of the called function is pushed first, and local arrays sit at lower addresses than it.

Definition 13.18

A buffer overflow is writing more data into a buffer than its size, so that the excess bytes spill over into adjacent memory. If a buffer on the stack overflows, the most dangerous victim is the return address.

/* small, deliberately buggy example */
void A(char *in) {
    char buffer[8];
    strcpy(buffer, in);   // NO bounds check
    return;
}
A(argv[1]);               // in: user input

This small, deliberately buggy function copies a string that comes from the user into an 8-byte array. strcpy does not know the size of the destination; it keeps copying until the terminating \0 in the source. As long as the input is 7 characters or fewer there is no problem: at most 8 bytes are written, terminator included, and the array does not overflow. If the input is longer, the excess bytes are written into the cells above the array. Because the array sits at a low address, the return address at a high address, and copying proceeds toward increasing addresses, the overflow heads straight for the return address (Figure 13.34).

HIGH addressLOW address (stack grows down)argv[1] pointerreturn addressCORRUPTED ✗frame pointerbuffer[4..7]buffer[0..3]write direction
Figure 13.34: The stack frame. The writing direction is upward; a long input corrupts first the frame pointer and then the return address.

When the function executes return, the processor reads the return address from the stack and jumps there. If the address has been corrupted with random bytes, the program most likely crashes with a segmentation fault (SIGSEGV). But an attacker who chooses the input can put an address of his own choosing in place of the return address. The flow of execution then goes wherever the attacker wants. In the classic attack, this address points to machine code that the attacker has placed in the buffer with the same input. If the program is setuid root or a network service, the attacker obtains a shell with root rights. The paper “Smashing the Stack for Fun and Profit” by Aleph One, published in 1996, described this technique in detail and began a generation of attacks.

Example 13.14

On a 64-bit machine, “Giresun-Ordu-Samsun” is copied with strcpy into the array char name[8]. There is no canary and no padding: the frame holds the 8-byte name, the 8-byte saved frame pointer (rbp), and the 8-byte return address. How many bytes are written, how many overflow, and how many bytes of the return address are corrupted?

  1. The string has 19 characters. strcpy writes 19 + 1 = 20 bytes, terminator included.
  2. The first 8 bytes, “Giresun-”, fit the array exactly. Since no \0 has come yet, copying continues.
  3. The next 8 bytes, “Ordu-Sam”, are written over the saved rbp.
  4. The remaining “sun” and \0 are written into the first four bytes of the return address: 73 75 6e 00. Because the machine is little-endian, these bytes are the low four bytes of the address; the address becomes …006e7573.

Of the 20 bytes in total, 20 − 8 = 12 have overflowed; 4 bytes of the return address are corrupted. When the function returns, the processor jumps to this invalid address and the program crashes. The values were verified with Python.

The fix is to limit the copy to the size of the destination. snprintf copies at most sizeof buffer − 1 characters and always adds a terminator.

void A(const char *in) {
    char buffer[8];
    snprintf(buffer, sizeof buffer, "%s", in);   /* at most 7 chars + '\0' */
}
Common mistake

Not counting the terminator. A string of 8 characters does not fit into an 8-byte array: strcpy writes 9 bytes and one byte overflows. Even a single overflowing byte can be exploited, for example by zeroing the lowest byte of the saved frame pointer. Bugs of this kind are called off-by-one errors.

13.6.2Defenses against buffer overflows

Buffer overflows have been known for more than forty years, and many layers of defense have been developed against them. Each defense targets a different step of the attack.

Stack canary
The compiler places a randomly chosen value, picked at process start, just below the return address. Before the function returns, it checks whether this value has been corrupted. An overflow that wants to reach the return address must first trample the canary. If corruption is seen, the program is stopped. In GCC this feature is known as stack-smashing protection (SSP).
DEP / NX
Data pages are marked non-executable in the page table (the NX bit on x86-64). Code injected into the stack does not run even if the processor jumps there; a page fault occurs. The rule that a page must not be both writable and executable is also called W^X.
ASLR
Address space layout randomization: the stack, the heap, and the libraries are loaded at different addresses on every run. The attacker cannot know which address to jump to. If the program itself is compiled as position-independent (PIE), its address is randomized too. On Linux, library placement in 64-bit processes carries 28 bits of randomness; about 268 million possibilities.
CFI
Control-flow integrity: indirect jumps and calls are allowed to go only to the valid targets that the compiler determined in advance.
Shadow stack
A copy of the return address is kept on a separate stack that the program cannot modify with ordinary write instructions. At return, the two addresses are compared. Intel CET and ARM GCS provide this in hardware. ARM's pointer authentication (PAC) and branch target identification (BTI) are separate protections with a similar aim.
Memory-safe languages
In languages such as Rust, Go, Java, and C#, array bounds and object lifetimes are checked by the compiler or the runtime. Buffer overflows cannot arise in these languages in the first place. This is the most fundamental solution.

As defenses developed, attacks changed too. When NX stopped code injected into the stack from running, attackers stopped bringing in new code. Instead they began to use code that already exists in memory. In a return-to-libc attack, the return address is redirected to the system() function in libc and given the argument “/bin/sh”. The more general form is return-oriented programming (ROP). The attacker finds small pieces of code (gadgets) ending in a ret instruction inside the program and its libraries. He writes the addresses of these pieces onto the stack one after another. Each piece executes a few instructions and moves on to the next with ret. With enough pieces, any computation can be performed. Because all this code already sits in executable pages, NX cannot stop this attack. ASLR hides the addresses of the pieces, and CFI and the shadow stack keep returns from going to unexpected places. This is why defenses are used together; none of them is enough alone.

13.6.3Code trace: the stack canary

Let us follow how the canary works byte by byte. In the code below, the canary lines are added not by the programmer but by the compiler; in real compiled code these lines are the function's prologue and epilogue instructions.

/* the compiler adds the canary lines */
void copy_in(const char *input) {
    long canary = __stack_chk_guard;
    char buf[8];
    strcpy(buf, input);
    if (canary != __stack_chk_guard)
        __stack_chk_fail();
}
/* input: "AAAAAAAABBBBBBBB" */

The function is called with the input “AAAAAAAABBBBBBBB”: 16 characters and a terminator. buf is 8 bytes. In the frame, from the low address toward the high one, are buf, the canary, the saved rbp, and the return address. The trace proceeds through the steps of Table 13.17.

Table 13.17: The state of the frame in the call copy_in("AAAAAAAABBBBBBBB"). The bytes are written in memory order (from the low address to the high one). The values were verified with Python.
Stepbuf[8]canarysaved rbpreturn address
call(undefined)(undefined)f0 c4 20 3a fd 7f 00 0096 11 40 00 00 00 00 00
prologue(undefined)00 5f b8 d4 e2 71 3c 9asamesame
first 8 bytesA A A A A A A Asamesamesame
next 8 bytesA × 8B B B B B B B Bsamesame
\0A × 8B × 800 c4 20 3a fd 7f 00 0096 11 40 00 00 00 00 00
exit check0x4242424242424242 ≠ 0x9a3c71e2d4b85f00 → __stack_chk_fail()
  1. Call. The call instruction pushes the return address (0x401196) onto the stack. The function's prologue saves the caller's frame pointer (0x7ffd3a20c4f0). In little-endian layout the lowest byte of an address comes first: 0x401196 appears in memory as 96 11 40 00 …
  2. Canary. The prologue that the compiler adds places the value __stack_chk_guard, chosen at random at process start, between buf and the saved rbp. In this example the value is 0x9a3c71e2d4b85f00. That its first byte, the lowest byte in memory, is 0x00 is a deliberate choice. Because string functions stop at this byte, the canary cannot be leaked by a string read and cannot be written verbatim by strcpy. The remaining 56 bits are random: 256 possibilities.
  3. First 8 bytes. strcpy writes “AAAAAAAA” into buf. So far there is no problem.
  4. Overflow. “BBBBBBBB” is written outside buf, over the canary. The canary is now 0x4242424242424242 (the ASCII code of B is 0x42).
  5. Terminator. \0 is written into the first byte of the saved rbp: f0 → 00. If the input were a little longer, the return address would be next. But the only way to reach the return address is to pass over the canary.
  6. Exit check. Before the function returns, the epilogue compares the canary on the stack with the value from process start. The two differ.
  7. Abort. __stack_chk_fail prints the message “*** stack smashing detected ***: terminated” and ends the process with SIGABRT. The corrupted frame is never returned to.
return address9611400000000000saved rbp00c4203afd7f0000canaryBBBBBBBBbuf[8]AAAAAAAAlow address →strcpy writes upward ↑0x4242424242424242 ≠ 0x9a3c71e2d4b85f00
Figure 13.35: The exit check: the canary on the stack (the B's) does not match the value from process start.

The gain of the canary is that it turns a code-execution attack into a crash. That is still a loss, because the service stops and availability is damaged. But the attacker cannot run his code. The canary has limits too. If the attacker can read the canary's value through another bug, he can write it back unchanged. If the overflow corrupts a function pointer instead of the return address, the canary never comes into play.

13.6.4Other memory and injection bugs

The buffer overflow is only one member of a broad family of bugs (Table 13.18).

Table 13.18: Memory and injection bugs.
VulnerabilityWhy it is dangerousCountermeasure
Format stringprintf(user): reads memory with %x, writes with %nprintf("%s", user)
Integer overflowlen = a + b wraps around and leads to a small allocationChecked arithmetic, size types
Use-after-freeAccess to freed memory (UAF)Ownership (Rust), smart pointers, quarantine
Double freeThe same block is freed twice; the heap is corruptedNULL after free, hardened allocator
Out-of-bounds readMemory leak such as HeartbleedBounds checking, fuzzing
Command/SQL injectionInput mixes into code or a queryParameterized queries, escaping, allowlists

In a format-string bug, the programmer passes the user's input directly to printf as the format string. If the user writes %x in the input, printf reads non-existent arguments from the stack. The contents of memory are thus dumped to the screen. %n, on the other hand, writes the number of characters printed so far to an address; with it the attacker can modify memory. In an integer overflow, the sum of two lengths exceeds a 32-bit variable and wraps around to a small number. The program allocates memory with this small value, then copies large data into that area, and an overflow occurs on the heap.

In use-after-free, the program keeps accessing a block it has freed through an old pointer. If the allocator has meanwhile given the block to another object, the attacker, by controlling the contents of that object, determines how the program interprets the old object. A large share of browser vulnerabilities are of this kind. The famous example of an out-of-bounds read is Heartbleed, found in OpenSSL in 2014. The server copied as many bytes into its reply as the length the client declared, without checking it. With every request, up to 64 KiB of its memory leaked, possibly including private keys and passwords.

The common root of these bugs is that data gets mixed with code or control information and that untrusted input is used unchecked. In the format string, data is interpreted as a format command. In SQL injection, a quote character typed by the user changes the structure of the query. The defense is common too: validate input, separate data from code, use memory-safe languages. Fuzzing tools, which feed the program random malformed inputs, also find bugs before attackers do.

13.6.5The TOCTOU race condition

Some vulnerabilities are not memory errors but timing errors. A program checks a condition and, some time later, performs an operation based on that check. If the condition can change between the two moments, the program is now acting on invalid information.

Definition 13.19

A TOCTOU (time of check to time of use) vulnerability is a race condition. An attacker can change the resource between the moment it is checked and the moment it is used.

/* TOCTOU: a setuid-root helper */
if (access(path, W_OK) == 0) {   // CHECK
    fd = open(path, O_WRONLY);     // USE
    write(fd, data, n);
}

The code is part of a setuid-root helper program. The program wants to prevent itself from writing, with root rights, to a file that the user who runs it has no write permission for. It uses the access call for this. access checks permission not against the effective ID but against the real ID: it answers the question “can ali write to this file?” If the answer is yes, the program opens the file with open. open, however, uses the effective ID, that is, root.

The problem is that the two calls resolve the file name separately (Figure 13.36).

  1. Check. /tmp/f is an ordinary file owned by Ali. access says the permission is there.
  2. Window. There is a small time gap between the check and the use. The scheduler may take the process off the CPU at exactly this point.
  3. Attack. In this gap the attacker deletes /tmp/f and puts in its place a symbolic link pointing to /etc/passwd: ln -sf /etc/passwd /tmp/f. The file name is the same, but the target has changed.
  4. Use. open("/tmp/f") resolves the name again and, following the link, opens /etc/passwd with root rights. write corrupts this critical file.
Victim (root)Attackeraccess("/tmp/f") → allowed(CPU yielded)ln -sf /etc/passwd /tmp/fopen("/tmp/f")→ now /etc/passwd!write(): passwd corruptedwindow
Figure 13.36: The TOCTOU timeline: in the window between check and use, the attacker replaces the file name with a symbolic link.

The window may be very short, but the attacker repeats the attempt thousands of times. On a multicore machine he improves his chances by running his own process on a separate core that keeps swapping the link. Hitting it once is enough.

The principle of the solution is not to resolve the name twice. The file is opened once, and all later checks are made on the same file descriptor. A descriptor stays bound to whichever file it was bound to at the moment it was opened; a later change of the name does not affect it. In addition, before opening, the program drops its privilege to the user's identity. Then the permission check is made not by access but by open itself, with the right identity. The O_NOFOLLOW flag refuses to open if the last component is a symbolic link.

/* fixed: the name is resolved once, the check is made on the same descriptor */
uid_t ruid = getuid();
seteuid(ruid);                                /* drop privilege first */
int fd = open(path, O_WRONLY | O_NOFOLLOW);   /* the kernel checks permission */
if (fd >= 0) {
    struct stat st;
    if (fstat(fd, &st) == 0 && S_ISREG(st.st_mode))
        write(fd, data, n);
    close(fd);
}

Programs working in a secure directory use the openat family to resolve the path relative to a directory descriptor; this also prevents the intermediate components of the path from being replaced.

Common mistake

Treating a smaller window as a solution. Because access and open are written one after the other, the window is measured in microseconds; but a small window only raises the number of attempts the attack needs. The solution is to close the window: the check and the use must be performed on the same object, with a single name resolution.

13.7Insider attacks

Some attacks come not from outside the system but from inside. The attacker is someone who develops or operates the system: a programmer, an administrator, a contractor. Because he has legitimate access, he has already got past all the outer defenses. This group has three classic methods.

Logic bomb
Malicious code that is triggered under a certain condition. The condition may be a date, or an event such as the programmer's name being removed from the payroll. Often a disgruntled employee plants it: the code runs every day, checks whether the programmer is still with the company, and if not, deletes files.
Back door
A hidden entry that bypasses authentication (Figure 13.37). Back doors can also be slipped into the supply chain. In 2024, a back door was noticed at the last moment in the xz compression library used by Linux distributions. The back door had been added by a contributor who had earned trust over years; it affected SSH authentication.
Login spoofing
The attacker runs a program that looks like the real login screen and walks away from the terminal. The user who arrives types his user name and password. The program records them, shows a “wrong password” message, and hands over to the real login screen. The user gets in on the second attempt and suspects nothing.
(a) Normal codeif (user_ok(name, pw)) grant_access();else deny();(b) Back-doored codeif (user_ok(name, pw) || eq(name, "zzz")) grant_access();else deny();“zzz” always gets in
Figure 13.37: (a) Normal login code; (b) a back-doored version that always grants login for the user name “zzz.”

Against login spoofing, a secure attention key is used. In Windows, no user program can capture the Ctrl+Alt+Del combination; these keys always directly summon the operating system's real login screen. If users are trained to press these keys before logging in, the real screen comes to the front even when a fake program is running on screen.

The defense against back doors is both organizational and technical. In code review, every change is seen by at least one other person. For critical changes, approval by two people is required. Reproducible builds let everyone obtain a byte-for-byte identical binary from the same source code. In this way it can be verified independently that the distributed program was built from the published source. Ken Thompson's 1984 Turing Award lecture shows the limit of this subject. Thompson describes a compiler that re-inserts the back door when it compiles itself and leaves no trace in the source code. In the end, every chain of trust begins somewhere with trusting a tool we did not write ourselves.

13.8Malware

Malware is the general name for programs that run against the wishes of the system's owner. These programs are designed to do harm, steal data, or consume resources. The vulnerabilities of the earlier sections are the doors these programs use to get into the system.

13.8.1Types

Malware is classified by how it spreads and by its purpose (Table 13.19).

Table 13.19: Types of malware.
TypeSpreadPurpose / behavior
VirusAttaches itself to another program; infects when the user runs that programCorrupts files, spreads
WormOn its own over the network; no user neededSpreads fast, consumes resources
Trojan horseInside a program that looks usefulOpens a back door, steals data
RansomwarePhishing, vulnerabilities, RDPEncrypts files, demands a ransom
RootkitInstalled after privilege is gainedHides itself and other malware
SpywareTrojan horse, bundled software, fake add-onCollects data, sends it away
Bot / botnetWorm + back doorDDoS, spam, mining on remote command

The difference between a virus and a worm is whom the spread depends on. A virus needs a carrier: it settles in another program or document and becomes active when that file is run or opened. A worm is an independent program. It copies itself from machine to machine through an unpatched service on the network, and the user does not need to do anything. The Morris worm of November 1988 affected a significant share of the machines connected to the Internet of the time within a few hours. WannaCry in 2017 was a worm that carried ransomware, and it spread through a vulnerability in Windows's file-sharing protocol.

The Trojan horse takes its name from the wooden horse of the Trojan War. It is a game, add-on, or “free” piece of software that looks useful and that the user installs of his own will. Because it runs with the user's rights, it reaches everything that user can reach. Spyware monitors the user's activities and sends them away. It can change the browser's home page or search engine, add unwanted toolbars, and open pop-up ads that cannot be stopped.

Today the boundaries are blurred. A modern piece of malware usually combines several types: it spreads like a worm, hides with a rootkit, connects to a botnet, and finally runs a ransomware payload.

13.8.2Parasitic viruses

The most common kind of classic virus is the parasitic virus, which settles in executable files. When infecting a file, the virus does two things: it adds its own code to the file and changes the program's entry point. When the program is run, the virus runs first, infects new files, and then jumps to the actual program. The user sees the program working normally and suspects nothing. Viruses fall into three kinds depending on where in the file they put their code.

Prepending
The virus code is added to the beginning of the program and the entry point is turned to the virus.
Appending
The virus is added to the end of the program; a jump to the virus is placed at the beginning of the program. This is the most common kind, because the rest of the program does not need to be shifted.
Cavity
Executable files contain unused gaps because of alignment. The virus splits itself into pieces and scatters them into these gaps. Because the file size does not change, detection becomes harder (Figure 13.38).
(d) cavityPrgVPrgVPrgVPrgThe entry point is redirected to the virus; the virus runs, then jumps to the real program
Figure 13.38: A cavity virus: the pieces are scattered over the unused areas of the program; the file size does not change.

There are other kinds. A companion virus does not touch the real program: in MS-DOS a .com file of the same name ran before the .exe, so it settles next to prog.exe under the name prog.com. Memory-resident viruses stay in memory and take over interrupt vectors. Boot-sector viruses run before the operating system. Device-driver viruses run in kernel mode. Macro viruses settle in the macros inside documents, and source-code viruses in source files before they are compiled. Most of these are historical today. Modern malware uses scripts, in-memory (fileless) techniques that never write a file to disk, and supply-chain paths.

13.8.3Ransomware

Ransomware is malware that encrypts the victim's data and demands money in return for the decryption key. Today it is one of the most destructive threats organizations face. A typical attack proceeds in five steps (Figure 13.39).

  1. Initial access. Usually through an attachment to a phishing e-mail, an unpatched service exposed to the Internet, or a stolen remote desktop (RDP) password.
  2. Spread. The malware runs and reaches as many machines as possible by lateral movement on the network. Attackers may spend days or weeks at this stage.
  3. Deleting backups. To prevent recovery, shadow copies and backups reachable over the network are deleted. This is why an offline or immutable backup is essential.
  4. Encryption. Files are locked with a strong symmetric cipher, for example AES. The symmetric key is encrypted with the attacker's public key or sent to the attacker's server. The victim is left with no copy of the key.
  5. Ransom note. Payment instructions are displayed on screen. In recent years, attackers also copy the data out before encrypting and threaten to publish it if payment is not made.
Phishing attachment / vulnerabilityRuns, spreadsDeletes backupsEncrypts filesRansom noteFiles encrypted with AESPayment ≠ guaranteed key; backups + patching are the only reliable defense
Figure 13.39: The ransomware attack chain. Payment does not guarantee that the key will be handed over; backups and patching are the only reliable defense.

Ransomware shows how sound cryptography can be used for a bad purpose. Used correctly, AES cannot be decrypted without the key. So once encryption has started there is little left to do; the defense must be prepared beforehand. Payment does not guarantee that the key will be handed over, and it encourages new attacks. The layers of defense are well-known tools: an immutable backup that follows the 3-2-1 rule, fast patching, MFA, network segmentation, and endpoint monitoring (EDR) that catches suspicious behavior.

13.8.4Rootkits and concealment

A rootkit is a collection of programs that an attacker who has settled in a system uses to hide his presence. It takes its name from the root account in UNIX. A rootkit hides files, processes, and network connections from the operating system and its tools. There are kinds depending on the layer it hides in (Figure 13.40).

Appalters ls, ps outputLibraryhijacks libc functionsKernelmodifies the system-call tableHypervisorputs the OS into a virtual machineFirmwareUEFI/peripheral; not erased by reinstallingdeeper = stealthier, harder to remove
Figure 13.40: The layers in which rootkits can hide. The lower it goes, the stronger the concealment and the harder the removal.
Application level
Tools such as ls and ps are replaced with versions that remove the malware's files and processes from their output. Easily caught by an integrity check.
Library level
Functions in libc are hijacked. For example, the function that reads directories skips certain names. All programs that use this library are deceived.
Kernel level
The rootkit is loaded as a kernel module and modifies the system-call table or the kernel's internal data structures. Every question asked of the kernel gets a false answer.
Hypervisor level
The rootkit slips the running operating system into a virtual machine without being noticed and runs beneath it. Seen from inside the operating system, no trace is visible.
Firmware level
It hides in UEFI firmware or in the firmware of a peripheral. It is not erased even if the operating system is reinstalled or the disk is replaced.

The deeper a rootkit settles, the more powerful it is, but also the harder it is to install. Scanning from inside is unreliable against rootkits in and below the kernel, because the rootkit answers the questions the scanner asks. The defense comes from several directions. Mandatory signed drivers ensure that only trusted modules are loaded into the kernel. Secure boot prevents a modified bootloader or kernel from running. Measured boot and the TPM record the digests of boot components and expose changes. As a last resort, the disk is scanned offline from a clean system.

13.8.5Antivirus and evasion techniques

Antivirus software and virus writers have been in a race for a long time. Every detection method has given rise to a new evasion technique.

The oldest method is signature scanning. A characteristic byte sequence, a signature, is extracted from the code of every known virus. The scanner looks for these sequences in files. It is fast and has few false alarms, but it catches only known viruses. Virus writers first turned to compression: when an infected program is compressed, the signature becomes invisible. Scanners responded by unpacking files and scanning their insides. Then encrypted viruses appeared: the body of the virus is encrypted with a different key in each copy, and only a small decryptor stays in the clear. Scanners then started looking for the signature of the decryptor.

The answer to this is polymorphic viruses (Figure 13.41). These viruses change the decryptor in every copy too. Different instruction sequences that do the same job are produced: no-op instructions are inserted, registers are swapped, the order of instructions is shuffled. Since no common byte sequence remains between two copies, the signature method does not work.

(e) polymorphicChanging decryptorEncrypted virusProgramPolymorphic: the decryptor differs in every copy → signatures fail, behavior analysis is needed
Figure 13.41: A polymorphic virus: the decryptor differs in every copy and the body is encrypted; no fixed signature remains.

Today's security software therefore uses several methods together.

Signature scanning
Catches known patterns quickly and with a low false-alarm rate; misses new ones.
Integrity checking
Stores digests of system files and notices any change.
Behavioral and heuristic analysis
Looks not at what a program is but at what it does. Encrypting hundreds of files in a short time, injecting code into other processes, and deleting shadow copies are suspicious actions.
Sandbox and cloud
A suspicious file is run in an isolated environment and its behavior is observed. The result is shared with all customers through the cloud.

13.9Defense and isolation

If we accept that bugs and vulnerabilities will never disappear completely, two paths of defense remain. The first is to ensure that only code from trusted sources enters the system. The second is to limit the harm that untrusted or compromised code can do. This section presents code signing for the first path, and sandboxes, containers, and mandatory access control for the second.

13.9.1Code signing

Code signing is the application of digital signatures to programs (Figure 13.42). The goal is to verify, before running a program, that it has not been modified and that it comes from the publisher it claims.

  1. Digest. The publisher computes the digest of the program.
  2. Signature. The digest is signed with the publisher's private key. The signature is distributed with the program.
  3. Distribution. The user receives the program and the signature. The publisher's certificate carries its public key and chains to a certificate authority.
  4. Verification. The operating system recomputes the digest and verifies the signature with the public key. If they match, the program has not been modified and is from that publisher.
PublisherOperating systemProgramdigestwith private keysignsignatureProgramsignatureverifies the signatureverifytrusted ✓
Figure 13.42: Code signing: the publisher signs the digest with its private key, and the operating system verifies it with the public key.

Most of today's systems rely on this foundation. Mobile app stores distribute only signed applications. In its 64-bit versions, Windows requires kernel drivers to be signed. The package managers of Linux distributions (apt, dnf) check the signature of every package against the distribution's key. Some platforms go even further and allow only signed code to run.

It is just as important what code signing does not prove. A signature shows who a program came from and that it was not modified on the way; it does not show that the program is harmless. If the publisher's signing key is stolen, or the publisher's build server is compromised, malicious code carries a valid signature too. Supply-chain attacks target exactly this point.

13.9.2Sandboxes

Definition 13.20

A sandbox is a method of running an untrusted program with limited rights, in an environment isolated from the rest of the system. Even if the program is compromised, the harm it can do stays limited by the boundaries of the sandbox.

The idea is a practical answer to Lampson's confinement problem. Figure 13.43 uses an old analogy: the program is in a prison, and a guard checks every system call it makes. Calls that are not allowed are blocked. The chroot jails of early UNIX and FreeBSD's jail mechanism were the first implementations of this thought.

Prison (jail)Confined programGuardEvery system callis checked by the guard;unauthorized onesare blockedModern sandbox• seccomp-bpf: allowed system calls• namespaces: separate PID/network/file views• cgroups: CPU/memory limits• capabilities dropped• SELinux/AppArmor profile
Figure 13.43: On the left, a confined program and its guard; on the right, the building blocks of a modern sandbox on Linux.

Today browser tabs, mobile applications, and many server services run in sandboxes. On Linux, a sandbox is a combination of several kernel mechanisms.

seccomp-bpf
Limits the system calls a process may make with a filter. For example, an image decoder may call only read, write, and exit. If it tries to make any other call, the kernel kills the process.
Namespaces
Give the process a separate view of the system. A process in a PID namespace sees only the processes in its own namespace; a network namespace has its own network interfaces, and a mount namespace has its own file-system tree.
cgroups
Limit the amount of CPU, memory, and I/O that a group of processes can use. They prevent denial of service through resource exhaustion.
Dropping capabilities
Even a process that starts as root drops all the Linux capabilities it does not need.
Mandatory access control
An SELinux or AppArmor profile separately restricts the files and resources the process can access.

13.9.3Containers

The structure that emerges when namespaces and cgroups come together is called a container (Figure 13.44). An application in a container sees a file system, a network stack, and a process tree of its own; it runs as if it were alone on a machine. In reality, however, all containers share the same kernel. Tools such as Docker and Kubernetes are built on these kernel features.

HardwareOne shared kernel (namespaces + cgroups + seccomp)Container 1AppLibrariesContainer 2AppLibrariesContainer 3AppLibrariesContainer 4AppLibraries
Figure 13.44: Four containers: each has its own application and libraries, but all share a single kernel.

Comparing a container with a virtual machine is instructive from a security point of view (Table 13.20). In a virtual machine, each guest runs its own kernel, and the guests are separated from each other by the hypervisor and by hardware. In a container, isolation rests entirely on the kernel's own features.

Table 13.20: Isolation of containers and virtual machines.
ContainerVirtual machine
IsolationKernel featuresHardware + hypervisor
OverheadLow, starts in a secondHigh, separate kernel
Attack surfaceKernel vulnerability = escape riskStronger boundary

The consequence of this difference is clear. If a vulnerability is found in the shared kernel, an attacker in a container can use it to escape the container and reach all the other containers on the same machine. In a virtual machine, a vulnerability in the guest kernel affects only that guest; escaping requires a second vulnerability in the hypervisor. For this reason cloud providers usually run the containers of different customers in separate virtual machines or in lightweight virtual machines (for example Firecracker).

Common mistake

Considering it harmless to run as root inside a container. If a user namespace is not used, root in the container is real root (uid 0) as far as the kernel is concerned. A process that gets out of the container through a configuration mistake or a kernel vulnerability takes over the whole machine. Container processes should also run with least privilege.

13.9.4Mandatory access control: SELinux and AppArmor

UNIX permissions and ACLs are discretionary access control (DAC): the permissions of a file are set by its owner, who can change them at any time. This has a weakness. A piece of malware running under Ali's account can also change the permissions of Ali's files, because as far as the kernel is concerned it is Ali. Mandatory access control (MAC) closes this weakness: the policy is set by the system administrator, and no process, not even root, can loosen its own restriction.

SELinux
Gives every subject and object a security label. Rules are written with type enforcement: “processes of type httpd_t may read files of type httpd_sys_content_t.” Very detailed and powerful, but complex. It also supports BLP-style multi-level security (MLS).
AppArmor
Uses per-application profiles based on file paths: “/usr/sbin/nginx may read only under /var/www/.” Easier to write and understand.

On Linux both systems use the kernel's Linux Security Modules (LSM) framework. The kernel places hooks in front of critical operations. When a process calls, for example, open, the usual DAC check is made first. If DAC allows, the LSM hook is called and the MAC policy is consulted (Figure 13.45). Both must say “yes” for the operation to go through. If DAC denies, MAC is never asked.

httpd processopen(/etc/shadow)DAC: rwx, ACLowner can changeMAC: SELinux/AppArmorpolicy, process cannot changeallowEACCESIf DAC denies, MAC is never askedboth must say “yes”
Figure 13.45: An open() request passes first through the DAC permission bits and then through the MAC policy in the LSM hook.
Example 13.15

A web server has been compromised through a vulnerability. The attacker can run commands with the server's user account. Two observations are made: (1) the attacker can freely change the permissions of a file belonging to the server with chmod; (2) he cannot access the files under /home even where the permission bits would allow it. Which check causes each behavior?

  1. (1) is DAC. The owner of the file is the server account, and under DAC the owner, even a malicious one, can change the permissions.
  2. (2) is MAC. The SELinux or AppArmor profile restricts the server process to the web files only. Even if the permission bits say “yes,” MAC says “no,” and the result is EACCES.

MAC restricts even a compromised process to the operations its profile allows. The attacker can reach only the files that profile defines. Android also runs SELinux fully in enforcing mode to separate applications from one another.

13.10Hardware-level security

All the earlier sections assumed that the operating system works correctly. But what if the operating system itself has been modified? Or if the hardware leaks information despite all the checks of the software? This section deals with the very bottom of the chain of trust.

13.10.1Secure boot and the TPM

When a computer is switched on, firmware, bootloader, kernel, and operating system run in turn. If an attacker can modify any link of this chain, he runs his own code before the operating system. When the operating system starts, it is this code that controls everything, and it is impossible to notice it from inside. Malware that settles in the boot process in this way is called a bootkit.

Definition 13.21

Secure boot means that every layer of the boot chain refuses to run the next one without verifying its digital signature. The chain rests on an immutable root of trust in hardware.

Hardware root of trustimmutableUEFI firmwaresignature ✓Bootloadersignature ✓Kernelsignature ✓Operating systemsignature ✓Each stage refuses to run the next without verifying its signature (chain of trust)Unsigned/modifiednot runTPMstores measurements, seals
Figure 13.46: The chain of trust: each stage verifies the signature of the next. An unsigned or modified component is not run. The TPM stores the measurements.

The chain works as follows (Figure 13.46). The root of trust in hardware verifies the signature of the UEFI firmware. UEFI checks the signature of the bootloader on disk against the keys in its own database. The bootloader checks the signature of the kernel, and the kernel that of the drivers it loads. If a bootkit has modified the bootloader on disk, UEFI cannot verify the signature and does not run the bootloader.

The complement of secure boot is the TPM (Trusted Platform Module). The TPM is a small security chip built into the motherboard or the processor. It contains platform configuration registers (PCRs). In measured boot, the digest of every component is taken before it runs and is extended into a PCR. Extending means hashing the old value of the register together with the new digest. The final value of a PCR is therefore a fingerprint of the whole chain together with its order, and it cannot be changed retroactively.

The TPM uses these measurements in two ways. The first is sealing: the disk-encryption key (for example a BitLocker or LUKS key) is sealed to particular PCR values. The TPM releases the key only if the system started in the expected state. If the bootloader has been modified, the measurement comes out different and the key is not unlocked. The second is remote attestation: the TPM signs the measurements with its own key and sends them to a remote server. The server can verify that the machine started with trusted software.

Common mistake

Treating secure boot and measured boot as the same thing. Secure boot does not run an unsigned component. Measured boot runs everything, but records what ran and does not unlock the key on an unexpected measurement. The TPM does not repair or block anything; it only measures, stores, and releases keys accordingly.

13.10.2Spectre, Meltdown, and side channels

In a covert channel, two processes cooperate on purpose. In a side channel, the victim is unaware of anything; the attacker measures indirect traces of its behavior.

Definition 13.22

A side channel is an attack path that leaks data through the indirect physical effects of computing it. These effects can be time, power consumption, cache state, electromagnetic emission, or sound.

A classic example is a function that compares a password character by character and stops at the first difference. An attempt that starts out right takes slightly longer; by measuring the times, the attacker finds the password character by character. This is the reason for constant-time comparison. The cache is also a powerful side channel. Whether a piece of data is in the cache can be told from the time it takes to access it: from the cache it arrives in a few nanoseconds, from main memory in about a hundred.

Meltdown and Spectre, announced in early 2018, combined this side channel with the processors' speculative execution (Figure 13.47). To gain speed, today's processors execute in advance instructions whose results are not yet certain. For example, before a branch condition is computed, the instructions in the predicted direction are executed. If the prediction turns out wrong, the processor rolls back the architectural results of these instructions, that is, the register values. But the data that the instructions brought into the cache stays in the cache.

Attacker processVictim / kernelsecret dataShared cacheCPU hardwarespeculative accessTiming measurementleaks bit by bitThe architectural result is rolled back but the cache trace remains → secret data is extracted
Figure 13.47: The architectural result of a speculative access is rolled back, but the trace it leaves in the shared cache remains and is read through timing measurements.

The attacker uses this as follows. He steers the processor into speculatively reading a secret byte that he has no right to access. The speculative code uses the value of this byte as an index into a large array and brings the line at that index into the cache. The processor notices the error and rolls the result back; the attacker never sees the secret byte. But he then accesses all the lines of the array and measures the times. The index of the line that comes back fast is the value of the secret byte. In this way Meltdown allowed a process in user mode to read kernel memory. Spectre made it possible to read the memory of another process, or of a protected region within the same process.

The countermeasures lie in both software and hardware. Against Meltdown, operating systems introduced kernel page-table isolation (KPTI): while in user mode, most of kernel memory is removed from the page table altogether. Against Spectre, microcode updates and speculation barriers added by the compiler are used. Most of these measures come at a performance price; the slowdown is noticeable in workloads heavy in system calls. These vulnerabilities also taught an important lesson: the correctness of protection mechanisms depends not only on the architectural specification but also on the implementation details of the hardware.

13.11Summary

  • The three basic goals of security are confidentiality, integrity, and availability; authenticity and accountability are added to them. A threat is a possible harm, a vulnerability is a weakness, an attack is an attempt to use it, and an exploit is the code that does so.
  • Network attacks include eavesdropping, replay, man-in-the-middle, and session hijacking. Their remedies are, respectively, encryption, single-use values, certificate-based authentication, and secure cookies.
  • Defense is built in depth; security claims rest on a TCB that should be kept small and on a reference monitor that checks every access.
  • Symmetric encryption is fast but needs a shared key; public-key encryption solves key distribution but is slow. Real systems use both together. Security rests on the key, not on the secrecy of the algorithm (Kerckhoffs).
  • A hash function is one-way and collision-resistant. In a digital signature, the digest is signed with the private key and verified with the public key. Certificates bind a public key to an identity. TLS 1.3 combines ephemeral Diffie-Hellman, certificates, and authenticated encryption in a single round trip.
  • In the Diffie-Hellman example (p = 23, g = 5, a = 6, b = 15), A = 8, B = 19, and the shared secret is 2. Square-and-multiply computes an n-bit exponent in n rounds.
  • The protection matrix is sparse; stored by columns it gives ACLs, by rows capability lists. Revocation is easy with ACLs, delegation with capabilities. UNIX permissions are a nine-bit ACL; a file descriptor is a capability.
  • By the least privilege principle, setuid programs drop their privilege permanently with setresuid as soon as their work is done. Linux divides root into about 41 capabilities.
  • Bell-LaPadula protects confidentiality: no read up and no write down. Biba protects integrity: no read down and no write up. Neither can close covert channels; only their bandwidth can be reduced.
  • Passwords are stored with a salted and slow hash (Argon2id): the salt makes mass attacks costly, and slowness makes each guess costly. MFA asks for two factors from different categories. A TOTP code is derived from HMAC(K, ⌊t / 30⌋) by dynamic truncation. A FIDO2 signature is bound to the origin of the site and is therefore phishing-resistant.
  • A stack buffer overflow corrupts the return address. Defenses are layered: the canary catches the corruption at return, NX blocks injected code, ASLR hides addresses, CFI and the shadow stack make ROP harder; the most fundamental solution is memory-safe languages.
  • In a TOCTOU vulnerability the resource changes between check and use; the solution is to resolve the name once and work on the same descriptor.
  • Insider attacks are logic bombs, back doors, and login spoofing. Malware includes viruses, worms, Trojan horses, ransomware, rootkits, spyware, and bots; polymorphic viruses defeat signature scanning.
  • Code signing verifies the source. Sandboxes and containers limit the harm; because a container shares the kernel, it is a weaker boundary than a virtual machine. MAC (SELinux, AppArmor) restricts even a compromised process to its profile.
  • Secure boot does not run unsigned components; the TPM stores measurements and seals keys to them. Spectre and Meltdown use the trace that speculative execution leaves in the cache as a side channel.

13.12Key terms

  • confidentiality / integrity / availability (CIA)
  • threat, vulnerability, exploit
  • denial of service
  • man-in-the-middle attack
  • defense in depth
  • trusted computing base (TCB)
  • reference monitor
  • encryption
  • public-key cryptography
  • cryptographic hash function
  • digital signature
  • certificate, public key infrastructure
  • forward secrecy
  • protection domain
  • access matrix
  • access control list (ACL)
  • capability
  • principle of least privilege
  • discretionary / mandatory access control
  • covert channel
  • authentication
  • salt
  • multi-factor authentication
  • buffer overflow
  • stack canary
  • address space layout randomization (ASLR)
  • malware
  • ransomware
  • sandbox
  • container, namespace
  • secure boot
  • side channel

13.13Test Yourself

  1. How is the word GIRESUN encrypted with the substitution key of Table 13.3? What does the ciphertext ZTLZ hide?

    Answer

    G → U, I → O, R → K, E → T, S → L, U → X, N → F: UOKTLXF. In the reverse direction Z → T, T → E, L → S, Z → T: TEST. Both Z's go to T; the frequencies are preserved again.

  2. In Diffie-Hellman, p = 23 and g = 5. Alice chooses a = 4 and Bob chooses b = 3. What are A, B, and the shared secret?

    Answer

    A = 54 mod 23 = 625 mod 23 = 4. B = 53 mod 23 = 125 mod 23 = 10. Alice: 104 mod 23 = 10000 mod 23 = 18. Bob: 43 mod 23 = 64 mod 23 = 18. The shared secret is 18.

  3. A friend says, “If Alice sends the document with an HMAC under a secret key she shares with Bob, that is a signature too.” Does this scheme provide integrity and non-repudiation?

    Answer

    It provides integrity: someone who does not know the key cannot modify the document and produce a valid code. It does not provide non-repudiation: since Bob also knows the key, Bob could have produced the same code. Alice can say “Bob produced this.” Non-repudiation needs a private key that only Alice knows.

  4. With the ACL of the code trace, what do access(G2, R|W) and access(ADM, W) return? If the decision expression were (h & req) != 0, would the result of the first call change?

    Answer

    G2's entry has h = 2; the request is 6. 2 & 6 = 2 ≠ 6, so deny (0). For ADM, h = 7, 7 & 2 = 2, so allow (1). With the faulty expression, 2 & 6 = 2 ≠ 0 and G2 would be allowed although it has no read right.

  5. A file has mode 754. Can group members modify the file? With umask 027, what modes do a new file and a new directory get?

    Answer

    754 = rwxr-xr--. The group's right is r-x; there is no write, so they cannot modify it. With umask 027 a file becomes 666 → 640 and a directory 777 → 750.

  6. For a process at the Secret level, which operation does BLP allow: reading an Unclassified announcement, or writing to a Confidential file? If the same process were at the Medium level in Biba, could it read an Internet file at the Low level?

    Answer

    In BLP, reading down is free; reading the Unclassified announcement is allowed. Writing to a Confidential file is a write down and is forbidden. In Biba, reading down is forbidden; a process at the Medium level cannot read the Low file.

  7. In a covert channel using file locking, the interval is reduced to 5 ms. What is the speed of the channel? How long does it take to leak a 2048-bit RSA private key?

    Answer

    1000 / 5 = 200 intervals per second, that is 200 bit/s. 2048 / 200 = 10.24 seconds.

  8. Passwords consist of 12 lowercase letters and are stored with plain SHA-256. At 1010 guesses per second, how long does it take in the worst case to find a single user's password? Does adding a salt change this time?

    Answer

    2612 ≈ 9.54 × 1016; divided by 1010 this is ≈ 9.54 × 106 seconds, about 110 days. A salt does not change the time for a single user; when all users are targeted, it multiplies the work by the number of users.

  9. At t = 1,000,000,000, what is the TOTP counter T? What 30-second window corresponds to this code?

    Answer

    1,000,000,000 / 30 = 33,333,333.3; T = 33,333,333. The window runs from T · 30 = 999,999,990 to 1,000,000,019.

  10. On a 64-bit machine, a function without a canary copies a 30-character string with strcpy into the array char name[16]. How many bytes overflow? How many bytes of the saved rbp and of the return address are corrupted?

    Answer

    With the terminator, 31 bytes are written; 31 − 16 = 15 bytes overflow. The first 8 corrupt the whole saved rbp, and the remaining 7 (including the last character and the \0) corrupt 7 bytes of the return address.

13.14Further reading

  • J. H. Saltzer and M. D. Schroeder, “The Protection of Information in Computer Systems”, 1975: the classic paper that first lists the principles of least privilege, fail-safe defaults, and complete mediation together. It is still relevant today.
  • R. Anderson, Security Engineering, 3rd ed.: treats security as an economic and human problem as much as a technical one. Its chapters on passwords, access control, and formal models contain real-world incident examples.
  • Aleph One, “Smashing the Stack for Fun and Profit”, Phrack 49, 1996: the historic text that shows the exploitation of a stack buffer overflow step by step. It helps one understand why today's defenses are needed.
  • P. Kocher et al., “Spectre Attacks: Exploiting Speculative Execution”, and M. Lipp et al., “Meltdown”, 2018: explain from the original source how speculative execution combines with the cache side channel.

13.15References

  1. A. S. Tanenbaum, H. Bos, Modern Operating Systems, 4th ed. (2014) / 5th ed. (2023), Pearson — Chapter 9: Security.
  2. A. Silberschatz, P. B. Galvin, G. Gagne, Operating System Concepts, 10th ed., Wiley, 2018 — Chapter 16: Security; Chapter 17: Protection.
  3. R. H. Arpaci-Dusseau, A. C. Arpaci-Dusseau, Operating Systems: Three Easy Pieces (OSTEP), ostep.org — the security chapters.
  4. R. Anderson, Security Engineering, 3rd ed., Wiley, 2020.
  5. J. H. Saltzer, M. D. Schroeder, “The Protection of Information in Computer Systems”, 1975.
  6. D. E. Bell, L. J. LaPadula (1973); K. J. Biba (1977) — formal security models. B. W. Lampson, “A Note on the Confinement Problem”, 1973.
  7. RFC 8446 (TLS 1.3), RFC 6238 (TOTP), RFC 9106 (Argon2); FIDO2/WebAuthn (W3C); NIST FIPS 203 (ML-KEM).
  8. Aleph One, “Smashing the Stack for Fun and Profit”, Phrack 49, 1996; Kocher et al., “Spectre”; Lipp et al., “Meltdown”, 2018.

Related pages: Chapter 13 slides · © Sercan Külcü. All rights reserved.