CSEC3616Cybersecurity Engineering

    Problem bank

    Every tutorial problem in the unit, with a worked solution behind each one where the unit has released one.

    188 of 188 shown

    • exam-q01

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 1 [2 points]

      A research laboratory’s director states: “Unpublished research results must be accessible only to members of the project that produced them.” The statement does not specify any software, hardware, or procedure for enforcing this requirement. Which component of the security engineering framework does this statement represent?

      • A. Assuarance
      • B. Incentives
      • C. Policy
      • D. Access Control
      • E. Mechanisms
      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Policy, mechanism, assurance and incentives.

    • exam-q02

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2 [2 points]

      A military communication link experiences an equipment fault. The commander has two options for sending urgent instructions: use a satellite relay, which is available but introduces a long communication delay, or switch to an unencrypted communication channel, which can deliver messages immediately but could be monitored by an opponent. The commander chooses the unencrypted channel so that the urgent instructions reach the intended recipients without delay. Which trade-off is most directly illustrated?

      • A. Integrity is prioritised over confidentiality
      • B. Confidentiality is prioritised over availability
      • C. Availability is prioritised over confidentiality
      • D. Authentication is prioritised over availability
      • E. Confidentiality is prioritised over integrity
      • security-goals

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Security goals.

    • exam-q03

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 3 [2 points]

      Which activities are passive attacks. Select all that apply.

      • A. An attacker records the timing and volume of encrypted messages to infer when a team is active, without interfering with the messages.
      • B. An attacker changes the delivery address in a message before forwarding it.
      • C. An attacker reads unencrypted messages travelling over a network, without modifying or delaying them.
      • D. An attacker retransmits a previously recorded instruction to make a system execute it again.
      • E. An attacker disrupts a communication channel so legitimate users cannot exchange messages.
      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • exam-q04

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 4 [2 points]

      An attacker phones an employee, says they are running a company-wide survey, and mentions the names of three colleagues in the same department who have “already completed it.” The employee answers questions that reveal sensitive information. Which psychological bias/influencing technique does this demonstrate?

      • A. Like bias
      • B. Social proof
      • C. Respect for authority
      • D. Reciprocity
      • E. Anchoring effect
      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Defaults, nudges and influence.

    • exam-q05

      Sample_Exam_Paper_Questions.pdf

      analyseconceptual

      Question 5 [2 points]

      A user signs in to a website using a biometric passkey process. Their user device asks for a fingerprint, then completes the login. Which statement correctly describes the roles of the fingerprint and the keys?

      • A. The website receives the fingerprint and compares it with a stored fingerprint template.
      • B. The device sends its private key to the website after the fingerprint matches.
      • C. The fingerprint itself is the public key registered with the website.
      • D. The website signs the challenge with the public key, and the device verifies it using the user’s fingerprint.
      • E. The fingerprint authorises local use of the private key; the website verifies the signed challenge using the registered public key.
      • authentication
      • public-key-cryptography

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Authentication, factors and one-time passwords.

    • exam-q06

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 6 [2 points]

      A company uses the following password policy:

      1. A password must be exactly eight characters long.
      2. The first character must be an uppercase English letter (A–Z).
      3. The next five characters must be lowercase English letters (a–z).
      4. The last two characters must be digits (0–9). Leading zeros in this two-digit ending are allowed.
      5. Repeated letters and repeated digits are allowed. Spaces and special characters are not allowed.

      For example, Abcdef07 satisfies the policy. Passwords are generated automatically, with each position chosen independently and uniformly from its permitted character set. An attacker knows the policy. Using H=log⁡2(N)H = \log_2(N), where NN is the number of equally likely valid passwords, what is the entropy of a generated password? Round to two decimal places.

      • A. 47.63 bits
      • B. 32.52 bits
      • C. 34.85 bits
      • D. 37.60 bits
      • E. 29.85 bits
      • passwords
      • entropy

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Password strength and generation.

    • exam-q07

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 7 [2 points]

      Which of the following best describes authorization?

      • A. Verifying a user’s identity with a password or fingerprint.
      • B. The allocation of a privilege to a party, or verifying that an entity is allowed an action.
      • C. A matrix with rows for users and columns for files showing r, w, and x rights.
      • D. The process of analysing an attacker’s motivations and capabilities.
      • E. Recording and auditing the actions performed by users on a system.
      • access-control
      • terminology

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Access control fundamentals.

    • exam-q08

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 8 [2 points]

      Which of the following statements about the set-user-ID (SUID) bit are TRUE? Select all that apply.

      • A. When set on an executable, the program runs with the privileges of the file’s owner rather than those of the user who launched it.
      • B. passwd and mount are examples of SUID-root programs.
      • C. ls -l shows a set SUID bit as an s in the owner’s execute position.
      • D. The SUID bit changes the process’s real UID to that of the file owner.
      • E. The SUID bit on a directory causes new files to inherit the directory’s owner.
      • unix-permissions
      • setuid
      • uids

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Unix and Linux permissions.

    • exam-q09

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 9 [2 points]

      In the Bell–LaPadula model, which property prevents a subject with Secret clearance from reading a document classified Top Secret?

      • A. The *-property (no write down)
      • B. The simple security property (no read up)
      • C. The invocation property
      • D. The simple integrity property
      • E. The tranquility property
      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • exam-q10

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 10 [2 points]

      A company develops an encryption system and publishes its complete algorithm for independent security analysis. The company assumes that an attacker knows the algorithm but does not know the secret key. Which principle does this design follow?

      • A. The principle of least privilege
      • B. Kerckhoffs’ principle
      • C. The separation of duties principle
      • D. The fail-safe defaults principle
      • E. The principle of security through obscurity
      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Cryptography basics and Kerckhoffs’s principle.

    • exam-q11

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 11 [2 points]

      Which of the following statements are TRUE? Select all that apply

      • A. Z11={0,1,…,10}\mathbb{Z}_{11} = \{0, 1, \ldots, 10\} with addition and multiplication modulo 11 is a finite field.
      • B. The multiplicative inverse of 7 modulo 11 is 8.
      • C. 6 has a multiplicative inverse modulo 9.
      • D. In Z12\mathbb{Z}_{12}, the element 5 is its own multiplicative inverse.
      • E. The set of integers Z\mathbb{Z} with ordinary addition and multiplication is a field.
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Finite fields, GF(p) and GF(2^n).

    • exam-q12

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 12 [2 points]

      A ciphertext produced by the Vigenère cipher contains a repeated trigram. The distance between the first and second occurrence is 40 characters, and between the second and third is 24 characters. Which key length is most consistent with both observations?

      • A. 3
      • B. 6
      • C. 8
      • D. 12
      • E. 24
      • symmetric-crypto

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The Vigenère cipher and the Kasiski examination.

    • exam-q13

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 13 [2 points]

      A simple cipher computes c=p⊕kc = p \oplus k. Given p=11001010p = 11001010 and k=01101100k = 01101100, which statements are TRUE?

      • A. c=10100110c = 10100110.
      • B. c⊕p=kc \oplus p = k.
      • C. An attacker who obtains one plaintext-ciphertext pair can recover the key.
      • D. Reusing kk to encrypt a second, different message is safe because the messages differ.
      • E. If the same key is used for two messages, C1⊕C2=P1⊕P2C_1 \oplus C_2 = P_1 \oplus P_2.
      • symmetric-crypto

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stream ciphers and the one-time pad.

    • exam-q14

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 14 [2 points]

      Bob wants to send Alice a message so that Alice, and anyone else, can be sure the message really came from Bob. Using public-key cryptography, which key does Bob use, and which key is used to verify?

      • A. Bob encrypts with Alice’s public key; only Alice verifies with her private key.
      • B. Bob encrypts with Alice’s private key; anyone verifies with Alice’s public key.
      • C. Bob encrypts (signs) with his own private key; anyone verifies with Bob’s public key.
      • D. Bob encrypts with his own public key; anyone verifies with Bob’s private key.
      • E. Bob encrypts with Alice’s public key; anyone verifies with Bob’s public key.
      • public-key-cryptography

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Digital signatures, DSA and RSA.

    • exam-q15

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 15 [2 points]

      Which of the following correctly states the Discrete Logarithm Problem on which Diffie-Hellman relies?

      • A. Given a large n=pqn = pq, find the prime factors pp and qq.
      • B. Given cc, ee, and nn with c=me mod nc = m^e \bmod n, find mm.
      • C. Given yy, gg, and a prime pp with y=gx mod py = g^x \bmod p, where gg is a primitive root of pp, find xx.
      • D. Given gg, xx, and pp, compute y=gx mod py = g^x \bmod p.
      • E. Given gg, yy, and a prime pp, determine whether gg is a primitive root of pp.
      • number-theory
      • public-key-cryptography

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-q16

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 16 [2 points]

      Let HH be a cryptographic hash function. Given a randomly chosen output value yy, it is computationally infeasible to find any input xx such that H(x)=yH(x) = y. Which property does this define?

      • A. Collision resistance
      • B. Second preimage resistance
      • C. Preimage resistance
      • D. Pseudo-randomness
      • E. One-wayness
      • hash-functions

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Preimage, second preimage and collision resistance.

    • exam-q17

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 17 [2 points]

      A protocol first encrypts the message, C=E(K2,M)C = E(K_2, M), and then computes a message authentication code over the ciphertext, T=MAC(K1,C)T = MAC(K_1, C), sending (C,T)(C, T). Which approach is being used, and which protocol uses this approach?

      • A. MAC-then-Encrypt; SSL/TLS
      • B. Encrypt-then-MAC; IPsec
      • C. Encrypt-and-MAC; SSH
      • D. Hash-then-Encrypt; SSH
      • E. Encrypt-then-Hash; HTTPS
      • message-authentication-codes
      • authenticated-encryption

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Authenticated encryption, GCM and CCM.

    • exam-q18

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 18 [2 points]

      Under the Dolev-Yao model, which of the following actions can an attacker perform?

      • A. Eavesdrop on messages transmitted over the network.
      • B. Delay, delete, modify, replay, or inject messages.
      • C. Decrypt a message encrypted under a key that the attacker does not possess.
      • D. Replay a previously captured message, even if the message is encrypted.
      • E. Modify a MAC-protected message without the receiver detecting the modification.
      • key-distribution

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The key distribution problem.

    • exam-q19

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 19 [2 points]

      Which of the following statements about authentication factors are TRUE?

      • A. A fingerprint is an example of the inherence factor (something you are).
      • B. A code sent by SMS to a phone is a possession factor, but it can be undermined because SMS can be rerouted through weaknesses in the SS7 signalling network.
      • C. A password is a possession factor because the user possesses knowledge of the password.
      • D. A security question such as “mother’s maiden name” is a knowledge factor whose answer may be predictable or discoverable from social networks.
      • E. Multi-factor authentication makes social engineering attacks impossible.
      • authentication

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Authentication, factors and one-time passwords.

    • exam-q20

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 20 [2 points]

      Which of the following statements about intermediate certificates and root CAs are TRUE?

      • A. Most websites hold certificates signed by an intermediate CA rather than directly by the root.
      • B. One reason for intermediates is to delegate signing authority to another organisation or region, creating a sub-CA.
      • C. Keeping the root CA’s private key offline and using the intermediate’s key for day-to-day issuance means that a compromised intermediate can be revoked without replacing the root in every user’s root store.
      • D. In modern browsers, all pre-installed root CAs are equally trusted, so compromise of any single root CA can be used to issue a fake certificate for any domain.
      • E. Users individually choose which CAs to trust when they install a browser.
      • certificate-authority
      • certificate-chain
      • pki

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public key infrastructure and revocation.

    • exam-q21

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 21 [2 points]

      Which TLS subprotocol signals that the following messages will be protected with the newly negotiated cryptographic parameters?

      • A. Alert Protocol
      • B. Change Cipher Spec Protocol
      • C. Record Protocol
      • D. Application Data Protocol
      • E. Handshake Protocol
      • tls
      • handshake

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The TLS handshake, 1.2 and 1.3.

    • exam-q22

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 22 [2 points]

      Which of the following are TRUE about TLS 1.3 compared with earlier versions of TLS? (Select all that apply.)

      • A. TLS 1.3 removed static RSA key exchange and uses ephemeral Diffie-Hellman key exchange to provide forward secrecy.
      • B. TLS 1.3 removed support for older, insecure cryptographic algorithms and cipher suites.
      • C. TLS 1.3 no longer uses certificates to authenticate servers.
      • D. TLS 1.3 provides confidentiality but does not provide message integrity.
      • E. TLS 1.3 requires a new public key to be generated for every message sent during a session.
      • tls-1-3
      • tls

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The TLS handshake, 1.2 and 1.3.

    • exam-q23

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 23 [2 points]

      Two branch offices connect their LANs over the Internet using IPSec tunnel mode between their gateway routers. Which of the following statements are TRUE? (Select all that apply.)

      • A. The entire original IP packet, including its header, is encapsulated as the payload of a new outer IP packet.
      • B. Routers on the Internet path can read the inner IP header to make forwarding decisions.
      • C. The outer packet may carry completely different source and destination addresses (the gateways) from the inner packet.
      • D. Hosts inside the LANs do not need to implement IPSec themselves.
      • E. This arrangement is the basis of a site-to-site Virtual Private Network.
      • network-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: IPSec: AH, ESP, IKEv2 and the two modes.

    • exam-q24

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 24 [2 points]

      A stateful firewall performs connection tracking using the “5-tuple”. Which fields make up the 5-tuple?

      • A. Source MAC, destination MAC, protocol, source port, destination port.
      • B. Source IP, destination IP, protocol, source port, destination port.
      • C. Source IP, destination IP, TCP flags, interface, action.
      • D. Source IP, destination IP, protocol, TTL, sequence number.
      • E. Source IP, destination IP, source port, destination port, packet length.
      • firewall
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stateful matching.

    • exam-q25

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 25 [2 points]

      In the C memory model, where is memory allocated by a call to malloc() placed?

      • A. The text (code) segment
      • B. The stack
      • C. The heap
      • D. The data segment
      • E. The read-only data segment
      • memory-layout
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Memory segments, the stack and function calls.

    • exam-q26

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 26 [2 points]

      Which of the following statements about a stack-based buffer overflow are TRUE? (Select all that apply.)

      • A. The overflow can occur when a function such as strcpy() copies more input bytes than the buffer allocated to hold the input can accommodate.
      • B. If 30 bytes of 0x41 are copied into a 10-byte buffer and the saved return address is reached, bytes from the input can overwrite the saved return address, potentially changing the address to which the function returns.
      • C. A buffer used to hold input can be located within a function’s stack frame, which can also contain the saved return address.
      • D. A stack-based buffer overflow requires the buffer used for input to be dynamically allocated using malloc().
      • E. The saved return address is stored outside the stack frame, so overflowing a buffer used for input cannot affect it.
      • buffer-overflow
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Exploiting a stack-based buffer overflow.

    • exam-q27

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 27 [2 points]

      A search page echoes the user’s search term straight into the response. An attacker sends a victim a link containing ?term=<script>...</script>; when the victim clicks it, the server includes the script in the page and the victim’s browser runs it. The script is never stored on the server. Which attack is this?

      • A. Stored XSS
      • B. Reflected XSS
      • C. SQL injection
      • D. CSRF
      • E. DOM-based XSS
      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • exam-q28

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 28 [2 points]

      A web page loads a JavaScript library from a Content Delivery Network (CDN), which is a service that hosts and delivers files for websites. Which of the following statements are TRUE? (Select all that apply.)

      • A. If the externally hosted script is replaced with a malicious copy, the including application can become vulnerable.
      • B. Subresource Integrity (SRI) lets the browser verify the script against an expected cryptographic hash and reject it if the hash does not match.
      • C. Loading a script from a CDN means the script is isolated from the including page and cannot access its data.
      • D. SRI encrypts the downloaded script before it is executed by the browser.
      • E. Content Security Policy (CSP) can specify a hash of an allowed script and block scripts that do not match an allowed hash.
      • web-security
      • supply-chain

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • exam-q29

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 29 [2 points]

      A web application passes a user-supplied field to a system ping command. An attacker enters localhost;cat /etc/passwd, and the application returns the contents of the password file. Which vulnerability class does this input exploit?

      • A. SQL injection
      • B. Command injection
      • C. Stored XSS
      • D. CSRF
      • E. Path traversal
      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • exam-q30

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 30 [2 points]

      Which of the following statements about RSA are TRUE? (Select all that apply.)

      • A. One factor that makes RSA secure is the computational difficulty of factoring the modulus nn into its two large prime factors.
      • B. RSA remains secure regardless of key size, so 512-bit keys are still acceptable.
      • C. Padding schemes such as OAEP are required to make RSA encryption secure in practice.
      • D. Any two distinct prime numbers may be chosen as pp and qq, regardless of their size or relationship.
      • E. RSA operations are much slower than symmetric encryption such as AES, which is why hybrid encryption schemes typically use RSA to establish or protect a symmetric key rather than encrypting large amounts of data directly.
      • rsa

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA security, attacks, padding and hybrid encryption.

    • exam-w1a

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 1: Public Key Cryptography [20 points]

      (a) [4 points] Let pp be a prime number. Explain what it means for an integer gg to be a primitive root modulo pp.

      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Discrete logarithms and primitive roots.

    • exam-w1b-i

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 1: Public Key Cryptography [20 points]

      (b) [10 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      i. If A computes their public key as 10, what is A’s private key? Explain your calculation. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w1b-ii

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 1: Public Key Cryptography [20 points]

      (b) [10 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      ii. If B computes their public key as 7, what is B’s private key? Explain your calculation. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w1b-iii

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 1: Public Key Cryptography [20 points]

      (b) [10 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      iii. Assuming A and B exchange their public keys, show the calculation A performs to find the shared key and calculate the shared key. (4 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w1b-iv

      Sample_Exam_Paper_Questions.pdf

      applynumeric

      Question 1: Public Key Cryptography [20 points]

      (b) [10 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      iv. Assuming A and B exchange their public keys, show the calculation B performs to find the shared key and calculate the shared key. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w1c

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 1: Public Key Cryptography [20 points]

      (c) [3 points] Explain what Perfect Forward Secrecy (PFS) is in the context of cryptographic protocols.

      • public-key-cryptography
      • key-distribution

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w1d

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 1: Public Key Cryptography [20 points]

      (d) [3 points] Explain how the Diffie-Hellman key exchange can be used to achieve Perfect Forward Secrecy.

      • public-key-cryptography
      • key-distribution

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • exam-w2a-a

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      a) This is a stateful firewall. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stateful matching.

    • exam-w2a-b

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      b) An external host can initiate an SSH connection to any internal host on the network. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • exam-w2a-c

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      c) An internal host at 203.10.45.50 can browse HTTPS websites on the Internet. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • exam-w2a-d

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      d) The web server at 203.10.45.10 can accept incoming HTTP and HTTPS connections from the Internet. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • exam-w2a-e

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      e) An external host can send a DNS response (UDP port 53) to an internal host at 203.10.45.100. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • exam-w2a-f

      Sample_Exam_Paper_Questions.pdf

      applyconceptual

      Question 2: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      f) An internal host at 203.10.45.20 can send a file to another internal host at 203.10.45.30 using any protocol. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • exam-w2b

      Sample_Exam_Paper_Questions.pdf

      recallconceptual

      Question 2: Network Security [20 points]

      (b) [4 points] In IPSec, there are two main security protocols: Authentication Header (AH) and Encapsulating Security Payload (ESP). Briefly explain the main difference between AH and ESP in terms of the security services they provide.

      • network-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: IPSec: AH, ESP, IKEv2 and the two modes.

    • exam-w2c

      Sample_Exam_Paper_Questions.pdf

      analyseconceptual

      Question 2: Network Security [20 points]

      (c) [4 points] Explain how TLS 1.3 achieves 1-RTT (one round-trip time) communication during the handshake, compared to TLS 1.2 which requires 2-RTT. In your answer, focus on the role of Diffie-Hellman key exchange parameters in the initial handshake. You may use a diagram if required.

      • tls-1-3
      • tls
      • handshake

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The TLS handshake, 1.2 and 1.3.

    • sw1-q1a

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (a) [2 points] Explain the Principle of Psychological Acceptability.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Psychological acceptability.

    • sw1-q1b

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (b) [2 points] A cloud storage provider enforces mandatory encryption for all client files to protect against insider threats. However, the encryption process makes file uploads and downloads significantly slower, frustrating users who need quick access. Explain what security goals are in contention here.

      • security-goals

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Security goals.

    • sw1-q1c-i

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (c) [6 points] Answer the following questions related to Fundamental Security Design Principles.

      i) Explain the Fundamental Security Design Principle of Open Design and how it relates to the Kerckhoffs’s Principle. (2 points)

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Fundamental design principles.

    • sw1-q1c-ii

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (c) [6 points] Answer the following questions related to Fundamental Security Design Principles.

      ii) Explain why it is important for a system’s security to follow the principle of Open Design. (2 points)

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Fundamental design principles.

    • sw1-q1c-iii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (c) [6 points] Answer the following questions related to Fundamental Security Design Principles.

      iii) Give one example where Kerckhoffs’s Principle is applied in practice. Explain your answer. (2 points)

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Cryptography basics and Kerckhoffs’s principle.

    • sw1-q1d

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (d) [4 points] Humans are susceptible to cognitive biases that can affect decision-making and security behaviour. Identify one cognitive bias, explain the bias, and describe a realistic scenario where an attacker could exploit it to compromise security.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Human error and cognitive bias.

    • sw1-q1e-i

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 1: Security Engineering Basics & Usability [20 points]

      (e) [4 points] A company enforces the following password policy for its employees:

      • Passwords must be exactly 8 characters long.
      • Characters can be uppercase letters (A–Z), lowercase letters (a–z), and digits (0–9).
      • No other symbols are allowed.

      i) Calculate the entropy (in bits) of a password under this policy. (2 points)

      • passwords
      • entropy

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Password strength and generation.

    • sw1-q1e-ii

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 1: Security Engineering Basics & Usability [20 points]

      (e) [4 points] A company enforces the following password policy for its employees:

      • Passwords must be exactly 8 characters long.
      • Characters can be uppercase letters (A–Z), lowercase letters (a–z), and digits (0–9).
      • No other symbols are allowed.

      ii) If an attacker can try 1 billion (10910^9) passwords per second, estimate the worst-case time to brute-force a randomly chosen password. Give your answer approximately in hours. (2 points)

      • passwords
      • entropy

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Password strength and generation.

    • sw1-q1f

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 1: Security Engineering Basics & Usability [20 points]

      (f) [2 points] Explain the concept of user conditioning in the context of security.

      • security-engineering
      • passwords

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Defaults, nudges and influence.

    • sw1-q2a-i

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (a) [10 points] Table 1 and Table 2 show mappings between users and clearances, and between objects and required clearnaces, respectively. The clearance levels increase as Public < Sensitive < Confidential < Secret < Top Secret. Only these mappings are defined; no other rule sets exist.

      UserClearance
      AlicePublic
      BobSensitive
      CarolConfidential
      DavidSecret
      FionaTop Secret

      Table 1: User Clearance Levels

      ObjectRequired Clearance
      meeting_notes.txtPublic
      budget_report.txtSensitive
      project_design.docxConfidential
      incident_log.txtSecret
      strategic_overview.pdfTop Secret

      Table 2: Object Clearance Requirements

      Refer to Table 1, and Table 2 and state if the following statements are True or False. Justify your answer.

      i. In a Bell-LaPadula model, Bob can read the file project_design.docx. (2 points)

      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • sw1-q2a-ii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (a) [10 points] Table 1 and Table 2 show mappings between users and clearances, and between objects and required clearnaces, respectively. The clearance levels increase as Public < Sensitive < Confidential < Secret < Top Secret. Only these mappings are defined; no other rule sets exist.

      UserClearance
      AlicePublic
      BobSensitive
      CarolConfidential
      DavidSecret
      FionaTop Secret

      Table 1: User Clearance Levels

      ObjectRequired Clearance
      meeting_notes.txtPublic
      budget_report.txtSensitive
      project_design.docxConfidential
      incident_log.txtSecret
      strategic_overview.pdfTop Secret

      Table 2: Object Clearance Requirements

      Refer to Table 1, and Table 2 and state if the following statements are True or False. Justify your answer.

      ii. In a Biba model, Carol can edit budget_report.txt. (2 points)

      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • sw1-q2a-iii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (a) [10 points] Table 1 and Table 2 show mappings between users and clearances, and between objects and required clearnaces, respectively. The clearance levels increase as Public < Sensitive < Confidential < Secret < Top Secret. Only these mappings are defined; no other rule sets exist.

      UserClearance
      AlicePublic
      BobSensitive
      CarolConfidential
      DavidSecret
      FionaTop Secret

      Table 1: User Clearance Levels

      ObjectRequired Clearance
      meeting_notes.txtPublic
      budget_report.txtSensitive
      project_design.docxConfidential
      incident_log.txtSecret
      strategic_overview.pdfTop Secret

      Table 2: Object Clearance Requirements

      Refer to Table 1, and Table 2 and state if the following statements are True or False. Justify your answer.

      iii. In a Bell-LaPadula model, Fiona can copy content from strategic_overview.pdf into incident_log.txt. (2 points)

      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • sw1-q2a-iv

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (a) [10 points] Table 1 and Table 2 show mappings between users and clearances, and between objects and required clearnaces, respectively. The clearance levels increase as Public < Sensitive < Confidential < Secret < Top Secret. Only these mappings are defined; no other rule sets exist.

      UserClearance
      AlicePublic
      BobSensitive
      CarolConfidential
      DavidSecret
      FionaTop Secret

      Table 1: User Clearance Levels

      ObjectRequired Clearance
      meeting_notes.txtPublic
      budget_report.txtSensitive
      project_design.docxConfidential
      incident_log.txtSecret
      strategic_overview.pdfTop Secret

      Table 2: Object Clearance Requirements

      Refer to Table 1, and Table 2 and state if the following statements are True or False. Justify your answer.

      iv. In a Biba model, Alice can write to meeting_notes.txt. (2 points)

      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • sw1-q2a-v

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (a) [10 points] Table 1 and Table 2 show mappings between users and clearances, and between objects and required clearnaces, respectively. The clearance levels increase as Public < Sensitive < Confidential < Secret < Top Secret. Only these mappings are defined; no other rule sets exist.

      UserClearance
      AlicePublic
      BobSensitive
      CarolConfidential
      DavidSecret
      FionaTop Secret

      Table 1: User Clearance Levels

      ObjectRequired Clearance
      meeting_notes.txtPublic
      budget_report.txtSensitive
      project_design.docxConfidential
      incident_log.txtSecret
      strategic_overview.pdfTop Secret

      Table 2: Object Clearance Requirements

      Refer to Table 1, and Table 2 and state if the following statements are True or False. Justify your answer.

      v. In a Bell-LaPadula model, David can read incident_log.txt. (2 points)

      • access-control

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Bell-LaPadula, Biba and MLS.

    • sw1-q2b-i

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 2: Access Control [20 points]

      (b) [6 points] Table 3 shows the current permissions on two files and two directories in a Linux system.

      NameTypeOwnerGroupPermissions
      deploy.shFilecaroladmins-rwxr-xr--
      report.pdfFiledavestaff-rw-r-----
      temp/Dirrootstaffdrwxrwxrwt
      shared/Dirrootstaffdrwxrws---

      Table 3: Current permissions on files and directories in the Linux system.

      i. Convert the permissions for the following entries into octal form (2 points)

      • deploy.sh
      • report.pdf
      • unix-permissions

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Unix and Linux permissions.

    • sw1-q2b-ii

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 2: Access Control [20 points]

      (b) [6 points] Table 3 shows the current permissions on two files and two directories in a Linux system.

      NameTypeOwnerGroupPermissions
      deploy.shFilecaroladmins-rwxr-xr--
      report.pdfFiledavestaff-rw-r-----
      temp/Dirrootstaffdrwxrwxrwt
      shared/Dirrootstaffdrwxrws---

      Table 3: Current permissions on files and directories in the Linux system.

      ii. Explain what the sticky bit on the temp/ directory does. (2 points)

      • unix-permissions

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Unix and Linux permissions.

    • sw1-q2b-iii

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 2: Access Control [20 points]

      (b) [6 points] Table 3 shows the current permissions on two files and two directories in a Linux system.

      NameTypeOwnerGroupPermissions
      deploy.shFilecaroladmins-rwxr-xr--
      report.pdfFiledavestaff-rw-r-----
      temp/Dirrootstaffdrwxrwxrwt
      shared/Dirrootstaffdrwxrws---

      Table 3: Current permissions on files and directories in the Linux system.

      iii. Explain what the setgid bit on the shared/ directory does. (2 points)

      • unix-permissions

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Unix and Linux permissions.

    • sw1-q2c

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 2: Access Control [20 points]

      (c) [4 points] Explain the confused deputy problem in the context of web browsers.

      • access-control
      • privilege-escalation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Middleware, databases and browsers.

    • sw1-q3a

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      You have given the public key of an RSA key pair (e,n)=(3,51)(e, n) = (3, 51) in the usual notation. Based on this information, answer the following questions. Use your calculators to do the modular computations (i.e., no need to do the exponentiation by squaring or the extended Euclidian algorithm).

      (a) [4 points] Calculate the private key of the given public key, i.e., (d,n)(d, n). Show your steps.

      • rsa
      • modular-exponentiation
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA.

    • sw1-q3b

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      You have given the public key of an RSA key pair (e,n)=(3,51)(e, n) = (3, 51) in the usual notation. Based on this information, answer the following questions. Use your calculators to do the modular computations (i.e., no need to do the exponentiation by squaring or the extended Euclidian algorithm).

      (b) [2 points] Encrypt the plaintext 8 using the public key and obtain the cipher text. Show your steps.

      • rsa
      • modular-exponentiation
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA.

    • sw1-q3c

      Sample_Written_Questions_1.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      You have given the public key of an RSA key pair (e,n)=(3,51)(e, n) = (3, 51) in the usual notation. Based on this information, answer the following questions. Use your calculators to do the modular computations (i.e., no need to do the exponentiation by squaring or the extended Euclidian algorithm).

      (c) [2 points] Demonstrate that you can obtain the plaintext back by decrypting using the private key. Show your steps.

      • rsa
      • modular-exponentiation
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA.

    • sw1-q3d

      Sample_Written_Questions_1.pdf

      analysenumeric

      Question 3: Public Key Cryptography [20 points]

      You have given the public key of an RSA key pair (e,n)=(3,51)(e, n) = (3, 51) in the usual notation. Based on this information, answer the following questions. Use your calculators to do the modular computations (i.e., no need to do the exponentiation by squaring or the extended Euclidian algorithm).

      (d) [6 points] Demonstrate the malleability property of RSA using the integer 3. Use the same the cipher text you obtained in b) for the plaintext 8. Explain your calculations.

      • rsa
      • modular-exponentiation
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA security, attacks, padding and hybrid encryption.

    • sw1-q3e

      Sample_Written_Questions_1.pdf

      analysenumeric

      Question 3: Public Key Cryptography [20 points]

      You have given the public key of an RSA key pair (e,n)=(3,51)(e, n) = (3, 51) in the usual notation. Based on this information, answer the following questions. Use your calculators to do the modular computations (i.e., no need to do the exponentiation by squaring or the extended Euclidian algorithm).

      (e) [6 points] Encrypt the plaintext 59 using the given RSA public key. You will find that the resulting ciphertext is the same as in part (b). This suggests that two different plaintexts produce the same ciphertext, raising ambiguity in decryption. Explain why this happens.

      • rsa
      • modular-exponentiation
      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: RSA.

    • sw1-q4a-i

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 4: Web security and Software Security [20 points]

      (a) [5 points] A news website allows users to post comments under each article. A user reports that when they view the comments section of a popular article, a script automatically executes in their browser and redirects them to a phishing site.

      i. Identify the exact type of attack happening in this scenario. Briefly justify your answer. (3 marks)

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw1-q4a-ii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 4: Web security and Software Security [20 points]

      (a) [5 points] A news website allows users to post comments under each article. A user reports that when they view the comments section of a popular article, a script automatically executes in their browser and redirects them to a phishing site.

      ii. Suggest a remediation strategy to prevent this attack. (2 marks)

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw1-q4b

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 4: Web security and Software Security [20 points]

      (b) [4 points] Briefly explain what Cross-Origin Resource Sharing (CORS) is and why it matters in web security.

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw1-q4c

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 4: Web security and Software Security [20 points]

      (c) [4 points] Explain how a Cross-Site Request Forgery (CSRF) attack works. Include the attacker’s goal and the mechanism of exploitation.

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw1-q4d-i

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 4: Web security and Software Security [20 points]

      (d) [4 points] A software team integrates a third-party library from an unverified GitHub repository into their project. Later, it is discovered that the library contained hidden malicious code that exfiltrated sensitive data.

      i. Identify the type of attack happening here. (2 marks)

      • supply-chain
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The software supply chain and zero days.

    • sw1-q4d-ii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 4: Web security and Software Security [20 points]

      (d) [4 points] A software team integrates a third-party library from an unverified GitHub repository into their project. Later, it is discovered that the library contained hidden malicious code that exfiltrated sensitive data.

      ii. Suggest a mitigation strategy to reduce the risk of such attacks in practice. (2 marks)

      • supply-chain
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The software supply chain and zero days.

    • sw1-q4e

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 4: Web security and Software Security [20 points]

      (e) [3 points] Explain how stack canaries help mitigate buffer overflow attacks.

      • buffer-overflow
      • defences

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Defences against buffer overflows.

    • sw1-q5a-i

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (a) Consider the below firewall table. It shows the rules of a firewall residing between the internet and a company network having the IP subnet, 203.0.113.0/24.

      RuleIfaceSrc IPDst IPProtocolSrc PortDst PortStateAction
      A******Est.Accept
      Binetexternal203.0.113.10TCP> 102380NewAccept
      Clan203.0.113.0/24externalTCP> 102380NewAccept
      Dlan203.0.113.0/24externalUDP> 102353NewAccept
      Elan203.0.113.0/24externalTCP> 102322NewAccept
      Flan203.0.113.0/24externalTCP> 1023443NewAccept
      G*******Drop

      For each of the below questions, first state whether the statement is TRUE or FALSE and then explain your answer.

      i. [2 points] The web server of the company accepts HTTPS connections coming from outside.

      • firewall
      • rule-order
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw1-q5a-ii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (a) Consider the below firewall table. It shows the rules of a firewall residing between the internet and a company network having the IP subnet, 203.0.113.0/24.

      RuleIfaceSrc IPDst IPProtocolSrc PortDst PortStateAction
      A******Est.Accept
      Binetexternal203.0.113.10TCP> 102380NewAccept
      Clan203.0.113.0/24externalTCP> 102380NewAccept
      Dlan203.0.113.0/24externalUDP> 102353NewAccept
      Elan203.0.113.0/24externalTCP> 102322NewAccept
      Flan203.0.113.0/24externalTCP> 1023443NewAccept
      G*******Drop

      For each of the below questions, first state whether the statement is TRUE or FALSE and then explain your answer.

      ii. [2 points] Company employees are not allowed to make outgoing SSH connections.

      • firewall
      • rule-order
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw1-q5a-iii

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (a) Consider the below firewall table. It shows the rules of a firewall residing between the internet and a company network having the IP subnet, 203.0.113.0/24.

      RuleIfaceSrc IPDst IPProtocolSrc PortDst PortStateAction
      A******Est.Accept
      Binetexternal203.0.113.10TCP> 102380NewAccept
      Clan203.0.113.0/24externalTCP> 102380NewAccept
      Dlan203.0.113.0/24externalUDP> 102353NewAccept
      Elan203.0.113.0/24externalTCP> 102322NewAccept
      Flan203.0.113.0/24externalTCP> 1023443NewAccept
      G*******Drop

      For each of the below questions, first state whether the statement is TRUE or FALSE and then explain your answer.

      iii. [2 points] To further improve the performance of the firewall, Rule G can be moved to the top of the table.

      • firewall
      • rule-order
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw1-q5a-iv

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (a) Consider the below firewall table. It shows the rules of a firewall residing between the internet and a company network having the IP subnet, 203.0.113.0/24.

      RuleIfaceSrc IPDst IPProtocolSrc PortDst PortStateAction
      A******Est.Accept
      Binetexternal203.0.113.10TCP> 102380NewAccept
      Clan203.0.113.0/24externalTCP> 102380NewAccept
      Dlan203.0.113.0/24externalUDP> 102353NewAccept
      Elan203.0.113.0/24externalTCP> 102322NewAccept
      Flan203.0.113.0/24externalTCP> 1023443NewAccept
      G*******Drop

      For each of the below questions, first state whether the statement is TRUE or FALSE and then explain your answer.

      iv. [2 points] An attacker can conduct an IP spoofing attack from inside of the company and conduct a DDoS attack against an external server.

      • firewall
      • rule-order
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Spoofing protection and rule shadowing.

    • sw1-q5a-v

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (a) Consider the below firewall table. It shows the rules of a firewall residing between the internet and a company network having the IP subnet, 203.0.113.0/24.

      RuleIfaceSrc IPDst IPProtocolSrc PortDst PortStateAction
      A******Est.Accept
      Binetexternal203.0.113.10TCP> 102380NewAccept
      Clan203.0.113.0/24externalTCP> 102380NewAccept
      Dlan203.0.113.0/24externalUDP> 102353NewAccept
      Elan203.0.113.0/24externalTCP> 102322NewAccept
      Flan203.0.113.0/24externalTCP> 1023443NewAccept
      G*******Drop

      For each of the below questions, first state whether the statement is TRUE or FALSE and then explain your answer.

      v. [2 points] This is a stateful firewall table.

      • firewall
      • rule-order
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stateful matching.

    • sw1-q5b

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (b) [4 points] What role does an X.509 certificate play in Transport Layer Security (TLS), and how does it help prevent person-in-the-middle attacks?

      • x509
      • tls
      • certificates
      • person-in-the-middle

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public-key certificates and X.509.

    • sw1-q5c

      Sample_Written_Questions_1.pdf

      applyconceptual

      Question 5: Network Security [20 points]

      (c) [4 points] What is forward secrecy in Transport Layer Security (TLS), and how is it achieved?

      • tls

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The TLS handshake, 1.2 and 1.3.

    • sw1-q5d

      Sample_Written_Questions_1.pdf

      recallconceptual

      Question 5: Network Security [20 points]

      (d) [2 points] Explain the difference between Transport and Tunnel modes in IPSec.

      • network-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: IPSec: AH, ESP, IKEv2 and the two modes.

    • sw2-q1a

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 1: Security Engineering Basics [20 points]

      (a) [2 points] Explain the fundamental security design principle Economy of Mechanism.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Fundamental design principles.

    • sw2-q1b

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 1: Security Engineering Basics [20 points]

      (b) [4 points] Explain the Principle of Psychological Acceptability.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Psychological acceptability.

    • sw2-q1c-i

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 1: Security Engineering Basics [20 points]

      (c) [5 points] Consider the following security scenarios. For each scenario, classify the attack as either an active attack or a passive attack.

      i A network attacker intercepts and records encrypted Wi-Fi traffic between a user and a web server for later analysis.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • sw2-q1c-ii

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 1: Security Engineering Basics [20 points]

      (c) [5 points] Consider the following security scenarios. For each scenario, classify the attack as either an active attack or a passive attack.

      ii An attacker sends a flood of malformed packets to a web server to make the service unavailable to legitimate users.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • sw2-q1c-iii

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 1: Security Engineering Basics [20 points]

      (c) [5 points] Consider the following security scenarios. For each scenario, classify the attack as either an active attack or a passive attack.

      iii An attacker secretly monitors keystrokes on a compromised machine without altering system behaviour.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • sw2-q1c-iv

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 1: Security Engineering Basics [20 points]

      (c) [5 points] Consider the following security scenarios. For each scenario, classify the attack as either an active attack or a passive attack.

      iv An attacker intercepts a legitimate authentication message and later retransmits it to gain unauthorised access to a server.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • sw2-q1c-v

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 1: Security Engineering Basics [20 points]

      (c) [5 points] Consider the following security scenarios. For each scenario, classify the attack as either an active attack or a passive attack.

      v An attacker captures network packets to infer communication patterns and user behaviour without changing any data.

      • security-engineering

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Attacks, attackers and attack surfaces.

    • sw2-q1d

      Sample_Written_Questions_2.pdf

      analyseconceptual

      Question 1: Security Engineering Basics [20 points]

      (d) [4 points] A high-frequency trading platform is required to record every transaction attempt to a centralised, tamper-proof audit server to meet regulatory compliance. During a period of extreme market volatility, the volume of trades increases tenfold. The delay caused by the system waiting for the audit server to confirm each log entry begins to stall trade execution, threatening to cause massive financial losses for clients and crashing the trading engine. To keep the platform online and responsive, the system automatically switches to a “Performance Mode” that suppresses all non-essential recording of transaction metadata until traffic stabilises.

      Identify the two security goals that are in contention in this scenario. Briefly explain how these goals conflict with each other.

      • security-goals

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Security goals.

    • sw2-q1e

      Sample_Written_Questions_2.pdf

      applynumeric

      Question 1: Security Engineering Basics [20 points]

      (e) [5 points] A company enforces the following password policy for its employees:

      • Passwords must be exactly 10 characters long.
      • The first 9 characters must be lowercase letters (a–z) or digits (0–9).
      • The final character must be one of the following special characters: #, $, %, &, or .

      Calculate the entropy (in bits) of a password under this policy.

      • passwords
      • entropy

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Password strength and generation.

    • sw2-q2a

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 2: Authentication and Key Establishment [20 points]

      (a) [3 points] Explain what a public key certificate is.

      • certificates
      • pki

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public-key certificates and X.509.

    • sw2-q2b

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 2: Authentication and Key Establishment [20 points]

      (b) [4 points] Explain what a root certificate is and how it can be identified.

      • certificates
      • certificate-authority

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public key infrastructure and revocation.

    • sw2-q2c

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 2: Authentication and Key Establishment [20 points]

      (c) [3 points] Explain the purpose of the root certificate store in an operating system or a web browser.

      • certificates
      • pki

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public key infrastructure and revocation.

    • sw2-q2d

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 2: Authentication and Key Establishment [20 points]

      (d) [2 points] The image below shows a common certificate error encountered while browsing the internet. Explain one possible reason for this error.

      Figure 1: Certificate Error. A browser warning page titled “Your connection is not private”, reading “Attackers might be trying to steal your information from revoked.grc.com (for example, passwords, messages, or credit cards)”, with the error code NET::ERR_CERT_AUTHORITY_INVALID.

      • certificates
      • tls

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Public key infrastructure and revocation.

    • sw2-q2e-i

      Sample_Written_Questions_2.pdf

      analyseconceptual

      Question 2: Authentication and Key Establishment [20 points]

      (e) [8 points] Suppose AA wants to establish an authenticated session with BB. They already share a secret key kk, and BB has a means to verify AA‘s password pp. Consider the following two protocols:

      Protocol 1: A→B:Enck(p)A \to B : \mathrm{Enc}_k(p)

      Protocol 2: A→B:Enck(p),MACk(p)A \to B : \mathrm{Enc}_k(p), \mathrm{MAC}_k(p)

      i For each of Protocol 1 and Protocol 2, determine whether it achieves the objective of establishing an authenticated session. Justify your answer separately for each protocol. (4 marks)

      • authentication
      • message-authentication-codes

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Authentication protocols and challenge-response.

    • sw2-q2e-ii

      Sample_Written_Questions_2.pdf

      analysedesign

      Question 2: Authentication and Key Establishment [20 points]

      (e) [8 points] Suppose AA wants to establish an authenticated session with BB. They already share a secret key kk, and BB has a means to verify AA‘s password pp. Consider the following two protocols:

      Protocol 1: A→B:Enck(p)A \to B : \mathrm{Enc}_k(p)

      Protocol 2: A→B:Enck(p),MACk(p)A \to B : \mathrm{Enc}_k(p), \mathrm{MAC}_k(p)

      ii Describe a modification to one of the protocols to achieve the objective. (4 marks)

      • authentication
      • message-authentication-codes

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Authentication protocols and challenge-response.

    • sw2-q3a

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 3: Public Key Cryptography [20 points]

      (a) [4 points] Let pp be a prime number. Explain what it means for an integer gg to be a primitive root modulo pp.

      • number-theory

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Discrete logarithms and primitive roots.

    • sw2-q3b

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 3: Public Key Cryptography [20 points]

      (b) [2 points] Using a prime number pp and a primitive root gg of pp, define the discrete logarithm problem.

      • number-theory
      • public-key-cryptography

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Discrete logarithms and primitive roots.

    • sw2-q3c-i

      Sample_Written_Questions_2.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      (c) [8 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      i If A computes their public key as 10, what is A’s private key? Explain your calculation. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q3c-ii

      Sample_Written_Questions_2.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      (c) [8 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      ii If B computes their public key as 7, what is B’s private key? Explain your calculation. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q3c-iii

      Sample_Written_Questions_2.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      (c) [8 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      iii Assuming A and B exchange their public keys, show the calculation A performs to find the shared key and calculate the shared key. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q3c-iv

      Sample_Written_Questions_2.pdf

      applynumeric

      Question 3: Public Key Cryptography [20 points]

      (c) [8 points] Suppose A and B are trying to establish a key using the Diffie-Hellman key exchange. The public parameters they are using are p=11p = 11 and g=2g = 2.

      iv Assuming A and B exchange their public keys, show the calculation B performs to find the shared key and calculate the shared key. (2 marks)

      • number-theory
      • public-key-cryptography
      • modular-exponentiation

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q3d

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 3: Public Key Cryptography [20 points]

      (d) [3 points] Explain what Perfect Forward Secrecy (PFS) is in the context of cryptographic protocols.

      • public-key-cryptography
      • key-distribution

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q3e

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 3: Public Key Cryptography [20 points]

      (e) [3 points] Explain how the Diffie-Hellman key exchange can be used to achieve Perfect Forward Secrecy.

      • public-key-cryptography
      • key-distribution

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Diffie-Hellman key exchange.

    • sw2-q4a-a

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      a) This is a stateful firewall. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stateful matching.

    • sw2-q4a-b

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      b) An external host can initiate an SSH connection to any internal host on the network. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw2-q4a-c

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      c) An internal host at 203.10.45.50 can browse HTTPS websites on the Internet. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw2-q4a-d

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      d) The web server at 203.10.45.10 can accept incoming HTTP and HTTPS connections from the Internet. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw2-q4a-e

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      e) An external host can send a DNS response (UDP port 53) to an internal host at 203.10.45.100. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw2-q4a-f

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 4: Network Security [20 points]

      (a) [12 points] A firewall sits between an internal network and the Internet. The internal network uses the public IP address range 203.10.45.0/24. The firewall has two interfaces: inet (connected to the Internet) and lan (connected to the internal network). Consider the following firewall rule table:

      RuleIfaceSrc IPDst IPProtoSrc PortDst PortStateAction
      Ainetexternal203.10.45.10TCP*80NewAccept
      Binetexternal203.10.45.10TCP*443NewAccept
      Clan203.10.45.0/24externalTCP*80NewAccept
      Dlan203.10.45.0/24externalTCP*443NewAccept
      Elan203.10.45.0/24externalUDP*53NewAccept
      F******Est.Accept
      G*******Drop

      For each statement below, indicate whether it is TRUE or FALSE and provide a brief explanation justifying your answer. Where applicable, reference the specific rule(s) involved in your reasoning.

      f) An internal host at 203.10.45.20 can send a file to another internal host at 203.10.45.30 using any protocol. (2 marks)

      • firewall
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Rule tables, first match and default policy.

    • sw2-q4b

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 4: Network Security [20 points]

      (b) [4 points] In IPSec, there are two main security protocols: Authentication Header (AH) and Encapsulating Security Payload (ESP). Briefly explain the main difference between AH and ESP in terms of the security services they provide.

      • network-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: IPSec: AH, ESP, IKEv2 and the two modes.

    • sw2-q4c

      Sample_Written_Questions_2.pdf

      analyseconceptual

      Question 4: Network Security [20 points]

      (c) [4 points] Explain how TLS 1.3 achieves 1-RTT (one round-trip time) communication during the handshake, compared to TLS 1.2 which requires 2-RTT. In your answer, focus on the role of Diffie-Hellman key exchange parameters in the initial handshake. You may use a diagram if required.

      • tls-1-3
      • tls
      • handshake

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The TLS handshake, 1.2 and 1.3.

    • sw2-q5a-i

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 5: Web security and Software Security [20 points]

      (a) [5 points] A popular e-commerce platform allows users to submit product reviews. An attacker submits a review for a high-traffic item that includes a malicious JavaScript payload within the text field. Whenever any customer or site administrator views that product’s page, the script executes automatically in their browser, attempting to steal their session cookies and redirect them to a fraudulent login page.

      i. Identify the exact type of attack happening in this scenario. Briefly justify your answer. (3 marks)

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw2-q5a-ii

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 5: Web security and Software Security [20 points]

      (a) [5 points] A popular e-commerce platform allows users to submit product reviews. An attacker submits a review for a high-traffic item that includes a malicious JavaScript payload within the text field. Whenever any customer or site administrator views that product’s page, the script executes automatically in their browser, attempting to steal their session cookies and redirect them to a fraudulent login page.

      ii. Suggest a remediation strategy to prevent this attack. (2 marks)

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw2-q5b

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 5: Web security and Software Security [20 points]

      (b) [4 points] Explain the Same-Origin Policy (SOP) and discuss its role as a fundamental security mechanism in web browsers.

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw2-q5c

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 5: Web security and Software Security [20 points]

      (c) [4 points] A web application takes user input from a search bar and inserts it directly into a database query string: "SELECT * FROM products WHERE name = '" + user_input + "';". Explain how an attacker could exploit this using SQL Injection (SQLi) to bypass authentication or leak data.

      • web-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

    • sw2-q5d-i

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 5: Web security and Software Security [20 points]

      (d) [4 points] Recently, it was discovered that a common Python library used in Large Language Model (LLM) applications was found to have a backdoor installed. If a company or developers were using this infected version of the litellm library, it could harvest their login tokens and exfiltrate them to an external server. The attack originated as a legitimate-looking update to the library, where the attacker had exploited vulnerabilities in the developer’s build tools to gain unauthorized access to the official publishing account.

      i. Identify the type of attack happening here. Briefly justify your answer. (2 marks)

      • supply-chain
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The software supply chain and zero days.

    • sw2-q5d-ii

      Sample_Written_Questions_2.pdf

      applyconceptual

      Question 5: Web security and Software Security [20 points]

      (d) [4 points] Recently, it was discovered that a common Python library used in Large Language Model (LLM) applications was found to have a backdoor installed. If a company or developers were using this infected version of the litellm library, it could harvest their login tokens and exfiltrate them to an external server. The attack originated as a legitimate-looking update to the library, where the attacker had exploited vulnerabilities in the developer’s build tools to gain unauthorized access to the official publishing account.

      ii. Suggest a mitigation strategy to reduce the risk of such attacks in practice. (2 marks)

      • supply-chain
      • software-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: The software supply chain and zero days.

    • sw2-q5e

      Sample_Written_Questions_2.pdf

      recallconceptual

      Question 5: Web security and Software Security [20 points]

      (e) [3 points] Explain how stack canaries help mitigate buffer overflow attacks.

      • buffer-overflow
      • defences

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Defences against buffer overflows.

    • t01-q1

      Tutorial1_questions.pdf

      recallconceptual

      Programming Satan’s Computer

      Ross Anderson and Roger Needham infamously described security engineering as “Programming Satan’s computer”. Explain the metaphor: why, in particular, is it “Satan’s computer”? 1-2 sentences are sufficient.

      • security-engineering
      Show worked solution

      The metaphor refers to a computer that acts intentionally maliciously, even to the degree that it reacts to the programmers’ behaviour and tries to find the best moment to thwart them. As a result, Security Engineering must tolerate the presence of an intelligent and hostile opponent.

    • t01-q2

      Tutorial1_questions.pdf

      analyseconceptual

      Safety/Reliability Engineering vs. Security Engineering

      Explain the difference between Safety and Reliability Engineerings and Security Engineering.

      • security-engineering
      Show worked solution

      Reliability Engineering or Safety Engineering try to address problems that we know at some point are going to happen, e.g. equipment failures, disk failures, power failures. For some of these we can even calculate failure probabilities: what is the probability of a disk failure after a certain number of years of operation? Many products release this information. Due to the predictable nature of these problems and the fact that we are expecting them, planning for such issues is much easier.

      On the other hand, it is difficult to predict and mitigate the threats coming from an active opponent, which is handled by Security Engineering.

    • t01-q3

      Tutorial1_questions.pdf

      analyseconceptual

      Security Goals - A

      You may wish to revisit the lecture recording to answer the following questions.

      a) True or false? Explain your answer in 1-2 sentences.

      • If you have the choice between secrecy and availability, and your system can only meet one of these goals simultaneously, always go for secrecy.
      • Authentication is the process of obtaining permission to access a file.
      • Privacy (in the context of internet) is my ability to conduct my online activities whilst being anonymous.

      b) Explain in 1-2 sentences.

      • Why does non-repudiation require secure timestamping in many cases?
      • Why is integrity of logfiles important to achieve accountability?
      • Why is it very hard to estimate the complete attack surface of a given system?
      • In the context of the last question, why is it important to remind yourself that security is a process?

      c) Break a protocol

      Danaerys tells Jon how he can enter the city. To enter the city, the guards will question him “Who goes there?” and Jon must reply with the secret passphrase (“The Lord of Winterfell”). Give a reason why this does not meet the definition of a cryptographic protocol and show how it can be broken.

      • security-goals
      Show worked solution

      a) True or false?

      • False. There are situations where availability is more important than secrecy. An example can be the military in a particular combat situation: it may matter more that commanders can communicate at all than the communication being accessible to eavesdroppers.
      • False. Authentication is about establishing the correctness of an identity. The process of obtaining permission to access a resource is authorisation.
      • False. Privacy is my ability to control what information I might share about me with other parties. What is described is anonymity, i.e. I want others to see and know what I am doing, I just don’t want them to know it was me.

      b) Explain in 1-2 sentences.

      • Why does non-repudiation require secure timestamping in many cases? Because it is possible for someone to claim that their computer system had been compromised at some point and it was the attacker who carried out some activity later. Secure timestamping by a third party (e.g. a TSA — Time Stamping Authority) provides a record of what happened at which time, and hence makes such claims much harder.
      • Why is integrity of logfiles important to achieve accountability? An attacker with access to a system can modify the log files to hide their traces. Hence, log files must be protected to ensure they provide a record of attacker activity (it is not always possible, however).
      • Why is it very hard to estimate the complete attack surface of a given system? This would require correctly enumerating every possible way a system can be breached. In practice that is usually not possible: today’s systems are too complex and one may easily overlook an attack vector.
      • In the context of the last question, why is it important to remind yourself that security is a process? What is not possible today may be possible tomorrow: the environment changes, and hence security is not static, but a process.

      c) Break a protocol

      This method provides no freshness. Someone could overhear the password being spoken and use it to enter (i.e. a replay attack).

    • t01-q4

      Tutorial1_questions.pdf

      analyseconceptual

      Security Goals - B

      Someone tells you that you can “just encrypt data” and you can be sure that the following security goals are achieved: confidentiality, integrity, authenticity, and access control. For each goal, explain if the person is right or wrong.

      • security-goals
      Show worked solution

      The easiest way to solve this is to start with the last three goals.

      • Confidentiality — right. Once the data is encrypted, confidentiality is guaranteed: without the key, the plaintext is not accessible.
      • Integrity — wrong. An attacker can make changes to the encrypted data, and it may still seem “plausible enough” when decrypted.
      • Authenticity — wrong. An attacker can make changes to the data, and there is no way to tell if it is authentic — see integrity. Authenticity is a special case of integrity, indicating that the data is exactly as it was when it was under the control of the originator. If a solution does not guarantee integrity, it does not guarantee authenticity. Solutions that do guarantee integrity may still not provide authenticity.
      • Access control — can be argued either way. This security goal overlaps with the others (or, alternatively, is more high-level). We tend to treat it as a security goal in its own right because it is all-important, even though it has many facets.
        • Right: we could argue that encryption controls access to the plain-text data.
        • Wrong: we can equally say that there is nothing about encryption that checks an attacker’s authorisation to modify or delete the data. So encryption provides only one aspect of access control.
    • t01-q5

      Tutorial1_questions.pdf

      analysedesign

      Sydney Opal Card

      You are likely familiar with the Sydney Opal Card system: a swipe card is used to “pay” and allow you to enter and leave the platforms via gates. Let us assume you were in charge when the system was planned. Using our reference framework of Policy, Incentives, Mechanism, and Assurance, please:

      • State two policies to achieve. One sentence per policy is fine.
      • State two incentives that work against those policies.
      • State one attack based on each incentive (see note below). It’s fine if the attack is described fairly generically (no need to refer to concrete technology that it attacks).
      • Give two mechanisms you can think of that will work against the attack based on the incentive.
      • State what assurance you place on each mechanism you have chosen.

      This question is intentionally open: you are free to choose policy and incentives, and you are free to make assumptions about how the transport system works. You are free to choose the attack based on the incentive (the one that your mechanism protects against). Policies, incentives, mechanism, and assurance do not have to be based on the electronic part of the system — it can also be entirely physical.

      • security-engineering
      • security-goals
      Show worked solution

      There are many possible answers. The following is an example.

      Policies

      • A high-level policy could be: customers must be billed correctly for their travel. If desired, that can be broken down into security goals relating to determining the correct amount to pay (integrity, accountability, authenticity etc.), but that was not necessary here as an answer — though a good exercise if you did it.
      • Another policy could be: the billing system must be available whenever a customer wants to travel.
      • Or: users’ travel data must be confidential and must be accessible only to authorised NSW Transport staff.

      Incentives

      • Attacker wants to free-ride.
      • Attacker wants to disturb the train system in Sydney.
      • Attacker wants to access some target users’ travel information.

      Attacks

      • Attacker forges an Opal card in someone else’s name, which is also linked to that person’s credit card. Alternatively: attacker breaks into an online account and resets a customer’s debt to 0.
      • Attacker stages a massive denial-of-service attack against the data centre that houses the accounting.
      • Attacker runs a phishing campaign targeting NSW Transport employees, hoping to harvest credentials for the customer database.

      Mechanisms

      • Forgery is difficult to defend against in an absolute sense. One needs Opal cards with chips that are hard to tamper with and, ideally, have a cryptographic mechanism that makes forgery detectable. History has shown that such systems are still hackable: it is a matter of effort. If the effort outweighs the benefit, the attacker is unlikely to try it — note how easily this balance is shaken if, e.g., the attacker finds a way to forge many cards and sell them. Defending against an attacker trying to break in means having intrusion detection in place, logging suspicious events, good passwords etc. — almost everything covered throughout the course.
      • Denial-of-service attacks are extremely hard to defend against: the natural asymmetry of internet-based services works against anything one can come up with. It is possible to make them less effective, however — for example, by having massive redundancy in place that can be spun up when needed (companies exist that provide exactly this security service). One can alternatively disconnect the internet interface from the internal Opal accounting, e.g. by having the internal accounting run autonomously for a few days without synchronising with the internet-facing systems or checking whether Opal cards are charged. That gives defenders time while keeping the system available. The drawback may be that, since it is not possible to check whether Opal cards are still charged, one may induce a certain potential loss from people who take the opportunity to run up a debt and then toss the Opal card. It may still be preferable to a wider outage, however.
      • Phishing is a common attack vector, discussed more in the usability lecture. Mechanisms to defend against it include deploying an email security solution that can flag suspicious emails, or conducting user training and awareness programs so employees can identify phishing emails. Again and again, various security incidents show that these two approaches are not perfect. Many high-profile network breaches — the iCloud celebrity-photo leak, the Sony hack, the Bangladesh Bank heist, and the eBay data breach — have been traced back to attackers infiltrating the network using well-researched, crafted phishing attacks that misled employees into entering their credentials.
    • t01-q6

      Tutorial1_questions.pdf

      analysedesign

      Designing a New Student Experience

      You have recently become the Head of the Higher Education Portfolio at your home university. Your first move is to cancel the subscription to the old “Whiteboard” system used to support lectures, enrolments, and grading. You replace it with something of your own design, called CAMPUS. In the following, refer to the framework for discussing security aspects that we introduced in the lecture.

      a) Incentives

      For each of the following actors, give an example incentive to attack or protect the system. Each incentive must be different.

      • The Vice Chancellor of the University
      • A student enrolled in a course
      • A Tutor of the same course
      • A Security guard in the CAMPUS data centre

      b) Policies

      For each of the following actors, give a possible security policy they might want to design and a security goal that relates to it.

      • The Vice Chancellor of the University
      • A student enrolled in a course
      • A tutor of the same course
      • security-engineering
      • security-goals
      Show worked solution

      a) Incentives

      There are multiple correct answers. Some examples are listed below.

      • The Vice Chancellor is concerned about the university remaining operational and its reputation (and hence all data must be protected), and therefore has an incentive to protect the system.
      • Students may be motivated to attack the system because they may wish to change their grades (or those of other students), or make the site unavailable so that they don’t have to do the quiz etc.
      • Tutors need to enter marks in order to do their job and get paid (so the site must be available). As such, they have an incentive to protect the system.
      • Similarly, the guard wants to be paid and keep their job.

      b) Policies

      Again several answers are possible.

      • The Vice Chancellor may ask that all data remain correct and secret, and that the privacy of all users and staff is guaranteed. The related security goals would be secrecy, integrity, and privacy.
      • The student may want the grading to be trackable, to understand whether someone manipulated their marks. This relates to accountability.
      • The tutor would like to work online and get paid in a timely manner. The security goal is availability.
    • t01-q7

      Tutorial1_questions.pdf

      recallconceptual

      Terminology

      a) Person-in-the-middle attack. What is a Person-in-the-middle, aka Man-in-the-middle, attack?

      b) Distributed Denial-of-Service. What is a Denial-of-Service attack? And a distributed one?

      c) Supply Chain Attack. What is a Supply Chain Attack?

      d) Security Goals. Tick all that are not classic security goals. Explain your choice.

      • Authenticity
      • Integrity
      • Deterrence
      • Authorisation
      • Confidentiality
      • Denial-of-service prevention
      • terminology
      • security-goals
      Show worked solution

      a) Person-in-the-middle attack

      An attack on the network (or some transmission bus) where the attacker manages to be between two communicating parties, usually carried out to eavesdrop on, or tamper with, the data. Examples are attacks on TLS (with broken authentication) or sniffing devices clipped into a data bus.

      b) Distributed Denial-of-Service

      An attack where someone over the network attempts to exhaust the resources of the victim. DoS attacks can be carried out by a form of malicious crowdsourcing (as demonstrated by LOIC), or by botnets. What usually happens is bots (compromised computers), or a group of people, start sending large volumes of requests towards a web service, and when the service can’t handle such a large load it becomes unavailable even for legitimate users. The term “distributed” applies when the attack is coordinated from different geo-locations, networks, and devices, so that it is extremely difficult to separate attack traffic from benign traffic. “Amplification” is a common tactic often used with DDoS attacks — e.g. DNS amplification, where the response is larger than the query and may even propagate to other DNS servers.

      c) Supply Chain Attack

      A supply chain attack is an attack in which the attacker inserts malicious code, or even a malicious component, into a trusted piece of software or hardware. By doing so, the attacker can hijack the victim’s distribution systems, turning any application they sell, any software update they push out, or even the physical equipment they ship to customers, into Trojan horses. With one well-placed intrusion, attackers can create a springboard into the networks of a supplier’s customers — sometimes numbering hundreds or even thousands of victims. Supply chain attacks are increasing because of their economies of scale. Recent examples include the SolarWinds and Kaseya attacks.

      d) Security Goals

      • Authenticity
      • Integrity
      • Deterrence
      • Authorisation
      • Confidentiality
      • Denial-of-service prevention

      The security goals discussed during the lecture are: confidentiality, integrity, authenticity, authorisation, accountability, non-repudiation, deniability, availability, and privacy. “Denial-of-service prevention” is only one aspect of the goal “availability”. “Deterrence” — the idea that the threat of punishment will deter people from committing crime and reduce the probability and/or level of offending in society — is not a security goal.

    • t01-q8

      Tutorial1_questions.pdf

      analyseconceptual

      Homework — ACSC Essential Eight

      Essential Eight by the Australian Cyber Security Centre (ACSC) is a series of baseline mitigation strategies recommended for organisations to improve their security posture. Implementing these strategies as a minimum makes it much harder for adversaries to compromise systems.

      • Find information about the Australian Cyber Security Centre (ACSC) Essential Eight maturity model.
      • Discuss how each strategy is applicable to a new superannuation provider.
      • essential-eight
      Show worked solution

      Find information about the ACSC Essential Eight maturity model

      The ACSC Essential Eight defines eight aspects of security with respect to Windows-based systems. They are:

      • Application Control
      • Application Patching
      • Restrict Administrative Privileges
      • Patch Operating Systems
      • Configure Microsoft Office Macro Settings
      • Using Application Hardening
      • Multi-Factor Authentication
      • Regular Backups

      When implementing the Essential Eight, organisations should first identify a target maturity level that is suitable for their environment. Organisations should then progressively implement each maturity level until that target is achieved.

      Discuss how each strategy is applicable to a new superannuation provider

      Being a high-risk company, the company must aim to reach maturity level three as quickly as possible.

      Optional aside

      The released solution stops there — it names the target maturity level but does not walk through each of the eight strategies individually for the superannuation provider. If you want the per-strategy reasoning, work through it yourself: a superannuation provider holds long-lived financial and personal records for members who may not check their balance for years, so integrity and availability of that data matter as much as keeping attackers out in the first place, which is why the tutorial’s answer jumps straight to the highest maturity level rather than treating the eight strategies as optional.

    • t02-q1a

      Tutorial_2_Questions.pdf

      applycommand

      Building a Password Cracker

      Passwords are intuitively understood by humans as a way to protect access to a resource. Just think of the fairy tale of Ali Baba! However, memorising them while maintaining unpredictability is the hard part — which is why “Open Sesame” is an exceptionally bad password.

      In this task, we will create a password cracker to get a feel for how passwords are constructed — and hacked. This will also serve as preparation for the next lecture. We’ll work from very naive approaches to more sophisticated ones.

      How Passwords Are Stored

      Passwords are usually stored as hashes (with salt), not as plain text. Password matching happens by comparing hashes, rather than plain-text passwords.

      Your tutor will explain:

      • What is hashing?
      • Why are passwords stored as hashes?
      • Why is salt important?
      • What is MD5 hashing? (hashing will be covered in detail later)

      Your Task

      You are given a set of MD5 hashes in hashes.txt for you to break. These are encoded versions of correct passwords.

      We provide skeleton code that allows you to compare a password against its corresponding MD5 hash.

      a) Brute-force

      The naive approach to cracking a password is to use brute force, trying all possible combinations of letters, digits, and special characters. For this task, we will limit ourselves to:

      • All letters in the English alphabet (both lowercase and uppercase)
      • Digits 0–9
      • Special characters #, !, and \$

      Complete the provided code template to brute force passwords up to a length of 4. Also, count the number of guesses required. Since the enumeration can take some time, we have included the MD5 hash of the password aA0# in the hashes_test.txt file. If your iteration loops are implemented correctly, you should find a match quite quickly. Once your code is working with this file, proceed to the hashes.txt file.

      Expected outcome: you should successfully crack a password of length 4. The number of guesses may vary depending on your implementation. If you follow the given code template, the brute-force process should take approximately 140–180 seconds on the provided Azure VM.

      from Crypto.Hash import MD5
      import string
      import sys
      import time
      
      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### TODO: Read the hashes from the file into a list
      hash_file = ## TODO
      hashes = ##
      
      ### TODO: Remove the newline characters
      hashes = ## TODO
      
      ### Function to obtain the MD5 hash of a given string - Do Not Change
      def break_password(password_attempt, md5_hash):
      
             return md5_hash == MD5.new(password_attempt.encode()).hexdigest()
      
      ### Building the alphabet
      alphabet_list_1 = ## TODO Get the ASCII lowercase letters as a list
      alphabet_list_2 = ## TODO Get the ASCII uppercase letters as a list
      alphabet_list_3 = ## TODO Get the digits as a list
      symbols = ## TODO Get the symbols as a list
      
      ### TODO: Build the final alphabet of all allowed characters
      alphabet = ## TODO Build the final alphabet list
      counter = 0
      
      ### Nested for loops for enumeration
      for a in alphabet:
      
             for b in alphabet:
                    for c in alphabet:
                           for d in alphabet:
                                  ## TODO: Increase the counter
                                  ## TODO: Build the password
                                  ## TODO: Obtain the hash
                                  if target_hash in hashes:
                                         print(
                                                "Match:", password, MD5.new(password.encode()).he
                                                "Attempt:", str(counter),
                                                "Time (Seconds):", (time.time() - start_time))

      Now try passwords of length 5.

      • Do you still get a hit?
      • How many guesses?
      • How much time did this take?

      Repeat the experiment for passwords of length 8. Don’t let the program run for more than a few minutes or so (stop the code using the STOP button above).

      • passwords
      • hashing
      Show worked solution
      from Crypto.Hash import MD5
      import string
      import sys
      import time
      
      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### TODO: Read the hashes from the file into a list
      hash_file = open("hashes.txt", "r")
      
      ### TODO: Read all lines from the file
      hashes = hash_file.readlines()
      
      ### TODO: Remove the newline characters
      hashes = [hashe.rstrip() for hashe in hashes]
      
      ### Function to obtain the MD5 hash of a given string - DO NOT Change
      def break_password(password_attempt, md5_hash):
      
             return md5_hash == MD5.new(password_attempt.encode()).hexdigest()
      
      ### Building the alphabet
      alphabet_list_1 = list(string.ascii_lowercase)   # Get the ASCII lowercase letters as a list
      alphabet_list_2 = list(string.ascii_uppercase)   # Get the ASCII uppercase letters as a list
      alphabet_list_3 = list(string.digits)            # Get the digits as a list
      symbols = ['#', '!', '$']                        # Get the symbols as a list
      
      ### TODO: Build the final alphabet of all allowed characters
      alphabet = alphabet_list_1 + alphabet_list_2 + alphabet_list_3 + symbols
      
      counter = 0
      
      ### Nested for loops for enumeration
      for a in alphabet:
      
             for b in alphabet:
                    for c in alphabet:
                           for d in alphabet:
                                  counter = counter + 1
                                  password = str(a + b + c + d)
                                  target_hash = MD5.new(password.encode()).hexdigest()
                                  if target_hash in hashes:
                                         print(
                                                    "Match:", password, MD5.new(password.encode()).hexdigest(),
                                                    "Attempt:", str(counter),
                                                    "Time (Seconds):", (time.time() - start_time))

      Match: Uq4C 6295d31334a99b0cc63c67e6bf15cedb — Attempt: 12704019 — Time: 44.182260274887085 seconds.

      Optional aside

      The released solution only records this length-4 result. It does not give fixed numbers for the length-5 or length-8 follow-up — the question’s own text says the guess count “may vary depending on your implementation,” and the actual time depends on the machine running it. Treat those two as open-ended: run your own completed loop and note what you observe, rather than looking for a specific figure here.

    • t02-q1b

      Tutorial_2_Questions.pdf

      applycommand

      Continuing the Tutorial 2 password-cracking exercise from t02-q1a: now cracking using a dictionary instead of brute force.

      b) Using a Dictionary — 1

      The above exercise should make you realise that brute force becomes very impractical very quickly. This is why almost all password cracking attempts try to leverage the weaknesses of the human mind: difficulty memorising random strings. Most users therefore tend to rely on words or common patterns they can remember.

      • Write code to load the dictionary file (located in the Tutorial 2 folder) into a suitable Python data structure.
      • What data structure should you use? Discuss this with your tutor if you are unsure!
      • What are the trade-offs?
      • Add code to try words from the dictionary as passwords. Do you get a hit?
      ### Start timing - Do Not Change
      start_time = time.time()
      
      #### TODO Open the dictionary file
      password_file = ## TODO
      
      #### TODO Read the password file into a list
      passwords = ## TODO
      
      #### TODO Remove the newline characters
      passwords = ## TODO
      
      #### TODO Enumerate through each password, generate the hash, and check w
      for password in passwords:
      
             ## TODO

      Now modify your code to be case-insensitive when checking passwords from the dictionary. Do you get more hits?

      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### TODO Get all uppercase versions of the above passwords
      pl_list = ## TODO
      
      ### TODO Get title case versions of the above passwords
      pt_list = ## TODO
      
      ### TODO Combine the three lists of passwords
      passwords_case = ## TODO
      
      #### Ignore case
      for password in passwords_case:
      
             ## TODO
      • passwords
      • hashing
      Show worked solution

      Lists or arrays are fine here, as in the context of this question we have to loop over all entries anyway. An optimisation would be to use a dictionary, with the keys being the first letters of each word — for example, all words starting with a could be stored as a list/array under the key a in the dictionary.

      There should be one more hit:

      Match: tutorial 0575c8d592fb7b088226750aceec2b4e

      from Crypto.Hash import MD5
      import string
      import sys
      import time
      
      ### Start timing - Do Not Change
      start_time = time.time()
      
      #### TODO Open the dictionary file
      password_file = open("dictionary.txt", "r")
      
      #### TODO Read the password file into a list
      passwords = password_file.readlines()
      
      #### TODO Remove the newline characters
      passwords = [password.rstrip() for password in passwords]
      
      #### TODO Enumerate through each password, generate the hash, and check whether it matches
      for password in passwords:
      
             target_hash = MD5.new(password.encode()).hexdigest()
             if target_hash in hashes:
      
                    print("Match:", password, MD5.new(password.encode()).hexdigest(),
                          "Time (Seconds):", (time.time() - start_time))

      Match: tutorial 0575c8d592fb7b088226750aceec2b4e — Time: 0.05276179313659668 seconds.

      Now modify your code to be case-insensitive when checking passwords from the dictionary. Do you get more hits?

      One more hit:

      Match: Tutorial 368fe771261fcb18f7988833c9294a20

      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### TODO Get all uppercase versions of the above passwords
      pl_list = [pl.upper() for pl in passwords]
      
      ### TODO Get title case versions of the above passwords
      pt_list = [pt.title() for pt in passwords]
      
      ### TODO Combine the three lists of passwords
      passwords_case = passwords + pl_list + pt_list
      
      #### Ignore case
      for password in passwords_case:
      
             target_hash = MD5.new(password.encode()).hexdigest()
             if target_hash in hashes:
      
                    print(
                            "Match:", password,
                            MD5.new(password.encode()).hexdigest(),
                            "Time (Seconds):", (time.time() - start_time)
                    )

      Match: tutorial 0575c8d592fb7b088226750aceec2b4e — Time: 0.050745248794555664 seconds. Match: Tutorial 368fe771261fcb18f7988833c9294a20 — Time: 0.10760664939880371 seconds.

    • t02-q1c

      Tutorial_2_Questions.pdf

      applycommand

      Continuing the Tutorial 2 password-cracking exercise from t02-q1b: trying combinations of two dictionary words.

      c) Using a Dictionary — 2

      You hopefully had a hit above, but you still haven’t found all the passwords yet. Try a further approach!

      • Add code to try combinations of words from the dictionary.
      • You may assume there are no spaces between them.
      • Do you get more hits? How much longer does it take?
      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### We need to use a loop break because the passwords list is really larg
      loop_break = False
      
      ### TODO Write two nested loops to go through the passwords twice
      for password1 in passwords:
      
             ## TODO
      • passwords
      • hashing
      Show worked solution

      There are hits. Students can either generate the combinations on the fly or write them out to a new dictionary — do not exceed available RAM; if you do, write the results out to disk. Also, write the code so that it exits after the first hit.

      Match: actress granny 173e06cdeafc20ff5704f595dd7650d8

      ### Start timing - Do Not Change
      start_time = time.time()
      
      ### We need to use a loop break because the passwords list is really large
      loop_break = False
      
      ### TODO Write two nested loops to go through the passwords twice
      for password1 in passwords:
      
             for password2 in passwords:
                    password = password1 + password2
                    target_hash = MD5.new(password.encode()).hexdigest()
                    if target_hash in hashes:
                            print(
                                   "Match:", password1, password2,
                                   MD5.new(password.encode()).hexdigest(),
                                   "Time (Seconds):", (time.time() - start_time)
                            )
                            loop_break = True
                            break
      
             if loop_break:
                    break

      Match: actress granny 173e06cdeafc20ff5704f595dd7650d8 — Time: 1.4428608417510986 seconds.

    • t02-q1d

      Tutorial_2_Questions.pdf

      applycommand

      Continuing the Tutorial 2 password-cracking exercise from t02-q1b: trying letter-substitution and suffix variants of dictionary words.

      d) Using a Dictionary — 3

      Some people replace letters with digits or special characters.

      • Add code to try words from the dictionary, but this time allow for letter substitutions (e.g., 4 for A or a).
      • Do you get more hits? How much more time does it take?
      • Now add code to also consider combinations of words and substitutions.
      • Do you get more hits?
      • How much time does it take?
      ### Start timing - Do Not Change
      start_time = time.time()
      
      for password in passwords:
             password = # TODO Replace A with 4
             password = # TODO Replace a with 4
             target_hash = # TODO
             if target_hash in hashes:
                    # TODO

      Some users append symbols such as ”#” and ”!” to common words.

      • Extend your code to check for added special characters, but limit yourself to two (’#’ and ’!’) and the special characters from the brute-forcing section above.
      • Do you get more hits? How much time does it take?
      for password in passwords:
             password = #TODO Add the suffix !#
             target_hash = #TODO
             if target_hash in hashes:
                    #TODO
      • passwords
      • hashing
      Show worked solution

      A good solution here is to perform the substitutions on the fly, i.e., have an extra method that is called to make substitutions.

      Match: fin4lly 68709d844aed1b2936a9fae66bc8b697

      ### Start timing - Do Not Change
      start_time = time.time()
      
      for password in passwords:
             password = password.replace('a', '4')
             password = password.replace('A', '4')
             target_hash = MD5.new(password.encode()).hexdigest()
             if target_hash in hashes:
                    print(
                            "Match:", password,
                            MD5.new(password.encode()).hexdigest(),
                            "Time (Seconds):", (time.time() - start_time)
                    )

      Match: fin4lly 68709d844aed1b2936a9fae66bc8b697 — Time: 0.02870035171508789 seconds.

      Some users append symbols such as ”#” and ”!” to common words. Extend your code to check for added special characters, but limit yourself to two (’#’ and ’!’) and the special characters from the brute-forcing section above. Do you get more hits? How much time does it take?

      There should be a hit.

      Match: hacking!# e9e8144285eca2c050ab0643409e79c2

      for password in passwords:
             password = password+"!#"
             target_hash = MD5.new(password.encode()).hexdigest()
             if target_hash in hashes:
                    print("Match: ", password, MD5.new(password.encode()).hexdigest())

      Match: hacking!# e9e8144285eca2c050ab0643409e79c2

    • t02-q1e

      Tutorial_2_Questions.pdf

      recallconceptual

      Continuing the Tutorial 2 password-cracking exercise from t02-q1a.

      e) Know the password strengths

      By now, you should have some idea of various password cracking methods and how long they take. The following table shows the times taken to crack different types of passwords. Note the following:

      • These calculations are based on a specific hardware setup. Advances in hardware and CPUs will speed things up.
      • These times are not guaranteed. Usually, there are defenses such as limits on the number of incorrect password attempts, restrictions on the number of requests from a single IP address, etc.
      • Also, the attacker’s options depend on the scenario. An attacker will have more time if they are trying to break into a hard disk to which they have physical access. Much longer and more complex passwords are required in such cases.

      Password cracking — source: hivesystems.com

      Optional aside

      The table itself did not survive extraction from the source PDF — only its caption (“Password cracking”) and the source link remain. Check the linked Hive Systems article, or the original Tutorial 2 handout, for the actual crack-time-by-length-and-character-set figures.

      • passwords
      • hashing
      Show worked solution
      Optional aside

      The released solution set has no separate entry for this part — it moves directly from part (d) to part (f). Part (e) is a reading checkpoint rather than a task with its own computed answer: the three notes above are what it is testing. A cracking-time table like this one describes one specific hardware setup with no defensive controls in place, so it is an upper bound on attacker effort, not a guarantee — and an offline attacker who has stolen a hash (say, from a disk image) has far more time available than one facing rate-limiting on a live login form. Part (g) puts these caveats to work in an actual calculation.

    • t02-q1f

      Tutorial_2_Questions.pdf

      recallconceptual

      Homework companion to the Tutorial 2 password-cracking exercise (t02-q1a).

      f) Homework — More on storing passwords

      Read more about salting, peppering, rainbow tables, and selecting password hashes by following this link.

      Optional aside

      The tutorial links out here; the link target did not survive text extraction from the source PDF.

      • passwords
      • hashing
      Show worked solution

      Salting

      Salting is the process of adding a random string (called a salt) to a password before hashing it.

      • Ensures that even if two users have the same password, their hashes will be different.
      • Makes pre-computed attacks (like rainbow tables) ineffective.
      • Storage: salts are typically stored in plaintext alongside the password hash, because they are not meant to be secret — their job is to make each hash unique.

      Peppering

      Peppering is similar to salting, but the pepper is kept secret (at the application or hardware level) instead of being stored with the password.

      • Adds an extra layer of security if the database is compromised.
      • Unlike salts, the pepper is common across all passwords and not stored in the database.

      Rainbow Tables

      Rainbow tables are large pre-computed lists that map possible passwords to their hash values.

      • Attackers use them to reverse hashes quickly.
      • Salting defeats rainbow tables, because each unique salt requires a new table.

      Selecting Password Hashes

      Use strong, slow password hashing functions such as:

      • bcrypt
      • scrypt
      • Argon2

      These are designed to be computationally expensive and resistant to brute-force attacks. Avoid using fast hash functions like MD5 or SHA-1 for password storage.

    • t02-q1g

      Tutorial_2_Questions.pdf

      applynumeric

      Homework companion to the Tutorial 2 password-cracking exercise (t02-q1a).

      g) Homework — Calculation of password cracking times

      A company uses 8-character passwords composed only of lowercase letters (a–z). This means there are 26 possible characters per position and 8 positions.

      1. Total password combinations. Calculate the total number of possible passwords.

      2. Cracking rates. Assume the following cracking speeds:

        • A CPU can attempt 100 million (1×1081 \times 10^8) hashes per second
        • A single GPU can attempt 5 billion (5×1095 \times 10^9) hashes per second
        • A multi-GPU rig with 8 GPUs can attempt 40 billion (4×10104 \times 10^{10}) hashes per second

        (a) Calculate how long it would take (in seconds, minutes, hours, and days) to try every possible password in the worst-case scenario for each of the three setups.

      3. Impact of salting. Suppose the company adds a unique 32-bit salt (4 bytes) to each user’s password. There are 1,000 users. (a) Explain how salting affects the attacker’s work if they want to crack all user passwords. (b) Recalculate the total number of combinations the attacker must try if they have to crack all users’ hashes individually. (c) How does this change the cracking time for each setup (CPU, GPU, multi-GPU)?

      Hint

      • Total combinations for unsalted passwords = 26826^8
      • When salting, the attacker must attack each user’s hash individually, because the salt is unique to each user.
      • Convert large numbers of seconds into days to interpret your answers.
      • passwords
      • hashing
      • entropy
      Show worked solution

      1. Total password combinations (unsalted)

      Passwords use 8 lowercase letters (a–z), so:

      268=208,827,064,57626^8 = 208,827,064,576

      or approximately 2.09×10112.09 \times 10^{11} possible passwords.

      2. Cracking times without salting

      CPU (100 million = 1×1081 \times 10^8 hashes/sec)

      Time = 2.09×1011÷1×108=2,0882.09 \times 10^{11} \div 1 \times 10^8 = 2,088 seconds

      • Seconds: 2,088 s
      • Minutes: 2,088÷60=34.82,088 \div 60 = 34.8 min
      • Hours: 34.8÷60≈0.5834.8 \div 60 \approx 0.58 hours

      Single GPU (5×1095 \times 10^9 hashes/sec)

      Time = 2.09×1011÷5×109=41.82.09 \times 10^{11} \div 5 \times 10^9 = 41.8 seconds

      • Seconds: 41.8 s
      • Minutes: 41.8÷60≈0.7041.8 \div 60 \approx 0.70 min

      Multi-GPU rig (8 GPUs = 4×10104 \times 10^{10} hashes/sec)

      Time = 2.09×1011÷4×1010=5.222.09 \times 10^{11} \div 4 \times 10^{10} = 5.22 seconds

      • Seconds: 5.2 s

      Observation: a multi-GPU rig is about 400x faster than a CPU in this example.

      3. Impact of salting (unique 32-bit salt per user)

      With unique salts:

      • Each user’s hash must be cracked individually.
      • For 1,000 users, total combinations:

      1000×268=1000×2.09×1011=2.09×10141000 \times 26^8 = 1000 \times 2.09 \times 10^{11} = 2.09 \times 10^{14}

      Recalculated times:

      CPU

      Time = 2.09×1014÷1×108=2.09×1062.09 \times 10^{14} \div 1 \times 10^8 = 2.09 \times 10^6 seconds

      • Seconds: 2.09×1062.09 \times 10^6 s
      • Days: 2.09×106÷86,400≈24.22.09 \times 10^6 \div 86,400 \approx 24.2 days

      Single GPU

      Time = 2.09×1014÷5×109=41,7652.09 \times 10^{14} \div 5 \times 10^9 = 41,765 seconds

      • Seconds: 41,765 s
      • Hours: 41,765÷3,600≈11.641,765 \div 3,600 \approx 11.6 hours

      Multi-GPU rig

      Time = 2.09×1014÷4×1010=5,2212.09 \times 10^{14} \div 4 \times 10^{10} = 5,221 seconds

      • Seconds: 5,221 s
      • Hours: 5,221÷3,600≈1.455,221 \div 3,600 \approx 1.45 hours

      Key takeaways

      1. Without salting:
        • Multi-GPU: 5.2 seconds
        • Single GPU: 42 seconds
        • CPU: 35 minutes
      2. With unique salts:
        • Multi-GPU: 1.45 hours
        • Single GPU: 11.6 hours
        • CPU: 24 days
      3. Salting dramatically increases the attacker’s workload, because each user’s hash must be attacked separately and precomputed tables (like rainbow tables) become useless.
    • t03-q1a

      Tutorial_3_Questions.pdf

      applycommand

      Q1: Access Control on Linux

      In the lecture, we learned that Linux implements access control via file permissions — this is the primary mechanism that users interact with. This concept is powerful because Linux (and UNIX) treats every object as a type of file.

      How file permissions work. File permissions are grouped and applied in a structured way:

      • A file always has an owner.
      • A file always has an associated group; this group may have the same name as the owner (for every user, there is also a corresponding group), but it can also be any group defined on the system.

      Permissions are then set for three categories:

      1. Owner — the user who owns the file
      2. Group — the group associated with the file
      3. Other — everyone else on the system

      Types of permissions. There are three fundamental file permissions in Linux:

      1. Read (r) — allows viewing or reading the contents of a file
      2. Write (w) — allows modifying or deleting the contents of a file
      3. Execute (x) — allows running a file (if it is a script or program)

      These permissions form the core of Linux access control and are critical for securing files and resources.

      a) Inspecting the list of users

      i) Take a look at the file /etc/passwd. Try to understand its contents. You can use commands like cat or more (e.g., cat /etc/passwd) to view its contents, or open it in an editor such as vi or nano. You can do this in a separate terminal. Alternatively, you can also use Jupyter Notebook. (In Jupyter, prefix command-line commands with !.)

      Example: !cat /etc/passwd

      ii) Try to log in as the tutorialuser1 user. What happens? i.e., use su tutorial1

      iii) Use sudo su to become root and then use the su command to switch to the tutorialuser1 user.

      i.e., run sudo su followed by su tutorialuser1. Use the command whoami to verify the current username. Use the command cd to navigate to the home directory of tutorialuser1. Use the command pwd to print the home directory path.

      iv) Try to log in (using the su command) as some of the entries that don’t appear to have human names (e.g., www-data, mail). What happens?

      v) Find out what the /usr/sbin/nologin entry in the /etc/passwd file does.

      • access-control
      • unix-permissions
      Show worked solution

      i) Take a look at the file /etc/passwd. What do you find in there?

      Each user has a single line entry. Each entry contains:

      • Username
      • An x indicating the password is stored in an encrypted form (in a separate file)
      • User ID (UID) and Group ID (GID)
      • Home directory
      • Default shell

      ii) Try to log in as the tutorialuser1 user.

      When you run su tutorialuser1, it will prompt you for the password of the tutorialuser1 account. Since you do not know the password, you will not be able to log in.

      iii) Use sudo su to become root and then use su to switch to tutorialuser1.

      1. Run sudo su to become the root user.
      2. Then run su tutorialuser1 to switch to the tutorialuser1 account.
      3. Use whoami and confirm that the logged-in user is tutorialuser1.
      4. Run cd to navigate to the home directory of tutorialuser1.
      5. Finally, use pwd to verify that you are in /home/tutorialuser1.

      iv) Try to log in as www-data or mail.

      Example: su mail (this will ask for a password, and you again don’t have the password). Become root and try again: sudo su, then run su mail or su www-data. You will see that you still can’t log in.

      This is because these users are not meant to log in from a normal shell. If you inspect the /etc/passwd file, you’ll notice that these accounts are configured with shells like /usr/sbin/nologin or /bin/false, which prevents interactive logins.

      v) What does the /usr/sbin/nologin entry do?

      It indicates that the user is not allowed to log in.

      Cross-reference: Unix and Linux permissions.

    • t03-q1b

      Tutorial_3_Questions.pdf

      analyseconceptual

      Q1 b) More on users

      i) While logged in as the ubuntu user (or any other normal user), try to view the /etc/shadow file. What happens?

      ii) How can you solve this issue?

      iii) What is the content of this file? Read about it here: https://www.cyberciti.biz/faq/understanding-etcshadow-file/

      iv) What are the file permissions for /etc/shadow, compared to /etc/passwd? If you don’t know how to find them, type man ls to learn about the command and the necessary options.

      • access-control
      • unix-permissions
      Show worked solution

      i) While logged in as ubuntu, try to view /etc/shadow.

      Command: cat /etc/shadow. You will get a permission denied error when trying to view /etc/shadow as a normal user.

      ii) How can you solve this issue?

      To view the contents of /etc/shadow, you need elevated privileges. Use the following command: sudo cat /etc/shadow

      iii) What is the content of this file?

      The /etc/shadow file stores encrypted password information and related security settings for user accounts. It is accessible only by the root user for security reasons.

      iv) What are the file permissions for /etc/shadow, compared to /etc/passwd?

      Commands to use:

      ls -ltr /etc/passwd
      ls -ltr /etc/shadow

      The outputs will look like this:

      -rw-r--r-- 1 root root   2026 Jul 29 05:51 /etc/passwd
      -rw-r----- 1 root shadow 1369 Jul 29 05:51 /etc/shadow

      The /etc/passwd file is owned by root. Root can read and write to it, while all others have read-only access.

      The /etc/shadow file is owned by root and belongs to the shadow group. Root can read and write to it, members of the shadow group can read it, and all others have no access.

      Explanation. The /etc/passwd file contains basic user account information that needs to be readable by all users and system processes, which is why it has read permissions for everyone. However, only the root user can modify it to protect against unauthorized changes.

      The /etc/shadow file stores sensitive password hashes and security-related information. Because of its sensitive nature, access is restricted to the root user and the shadow group only. This restriction protects user credentials from being exposed to normal users or processes, enhancing system security.

      Cross-reference: Unix and Linux permissions.

    • t03-q1c

      Tutorial_3_Questions.pdf

      applycommand

      Q1 c) Executing files

      • List the permissions of the yes program. Hint: you can find the location of this file by typing which yes into your terminal.
      • Why are you able to execute it?
      • unix-permissions
      Show worked solution
      tutorialuser1@lab22YQ9P:$ which yes
      /usr/bin/yes
      tutorialuser1@lab22YQ9P:$ ls -ltr /usr/bin/yes
      -rwxr-xr-x 1 root root 39256 Sep 5 2019 /usr/bin/yes

      Since there is x permission for the owner, group, and others, all users can execute it.

    • t03-q1d

      Tutorial_3_Questions.pdf

      applycommand

      Q1 d) Setting permissions for files

      An owner can set permissions for a file using the chmod command. Interestingly, there are several ways to specify permissions. For example, one can use the syntax g+r / g-r to add or remove read permission for the group (similarly, u+r and o+r apply to the user and “others”).

      Another approach is to write the permissions in octal notation, where the first digit refers to the user, the second to the group, and the third to “others”. Each digit encodes three bits:

      A value of 7 in octal is 111 in binary, meaning read, write, and execute permissions are all granted. For example, chmod 777 would give full permissions to the user, group, and others.

      Values of each permission setting:

      Value (Octal)Value (Binary)Permission granted
      1001Execute
      2010Write
      4100Read

      Question: What would be the command to set the permissions of a file to match those of /etc/passwd?

      • unix-permissions
      Show worked solution
      ubuntu@lab22YQ9P:$ ls -ltr /etc/passwd
      -rw-r--r-- 1 root root 2026 Jul 29 05:51 /etc/passwd

      The permission string -rw-r--r-- means:

      • Owner (user): read and write (rw-)
      • Group: read-only (r--)
      • Others: read-only (r--)

      This translates to octal 644 (User = 6, Group = 4, Others = 4).

      touch test_file.txt        # Create a new file named test_file.txt
      chmod 644 test_file.txt    # Change the permissions to 644
      ls -ltr test_file.txt      # Check the set permissions

      The output will show test_file.txt now has the same permissions as -rw-r--r-- /etc/passwd.

      Cross-reference: Unix and Linux permissions.

    • t03-q1e

      Tutorial_3_Questions.pdf

      applycommand

      Q1 e) Owners and groups

      Now let’s explore file ownership in more detail.

      • How can you change the owner or group of a file?
      • Try changing the owner of a file that belongs to root. Were you successful?
      • Now try the same operation as the root user. Does it work this time?
      • access-control
      • unix-permissions
      Show worked solution
      ubuntu@lab22YQ9P:$ ls -ltr test_file.txt
      -rw-r--r-- 1 ubuntu ubuntu 0 Jul 29 06:20 test_file.txt
      
      ubuntu@lab22YQ9P:$ sudo chown root:root test_file.txt
      ubuntu@lab22YQ9P:$ ls -ltr test_file.txt
      -rw-r--r-- 1 root root 0 Jul 29 06:20 test_file.txt

      As shown above, running chown with sudo (as root) successfully changes the owner and group of the file to root. Once you do the change, you will not be able to change the ownership of a file owned by root as a normal user.

      Cross-reference: Unix and Linux permissions.

    • t03-q2a

      Tutorial_3_Questions.pdf

      applycommand

      Q2: Potential problems with setuid/setgid

      Back to file permissions again: setting permissions for a file doesn’t just involve 3 octal digits (e.g., 444, 761, …); it actually involves 4 digits! An extra digit can be placed at the start of the command, which is used to set the following special bits:

      • setuid bit (4): when this bit is set on an executable file, the program runs with the privileges of the file’s owner rather than the user who runs it. This is often used for programs that need elevated privileges (e.g., passwd).
      • setgid bit (2): similar to setuid, but it applies the file’s group privileges instead of the user’s. For directories, it ensures that files created inside inherit the directory’s group.
      • sticky bit (1): on directories, this bit ensures that only the file’s owner (or root) can delete or rename the files inside, even if others have write permissions.

      Note: misuse of the setuid or setgid bits can lead to security vulnerabilities because they can grant elevated privileges.

      a) Setting the bits

      • How can you set a file to have both the setuid and setgid bits enabled?
      • Provide the command(s) to set a file’s owner to be bertie and to enable its setuid bit. (Hint: you may need to create the user bertie first using man adduser.)
      • setuid
      • unix-permissions
      Show worked solution
      1. Create a file named my_program:
      touch my_program
      1. Set both setuid and setgid bits on a file:
      chmod 6755 my_program

      6 at the start sets both setuid (4) and setgid (2) bits. 755 sets rwxr-xr-x (owner: read/write/execute; group and others: read/execute).

      ls -ltr my_program
      -rwsr-sr-x 1 ubuntu ubuntu 12345 Jul 29 06:30 my_program

      Notice the s in the owner and group execute positions, indicating the setuid and setgid bits are set.

      1. Set a file’s owner to bertie and enable the setuid bit:
      sudo adduser bertie   # if bertie does not already exist
      sudo chown bertie my_program
      sudo chmod 4755 my_program
      ls -ltr my_program
      -rwsr-xr-x 1 bertie ubuntu 12345 Jul 29 06:35 my_program

      Here, 4 at the start sets only the setuid bit, and 755 applies normal file permissions. The lowercase s (or uppercase S if execute is not set) in the owner’s execute position shows the setuid bit is enabled.

      Cross-reference: Unix and Linux permissions.

    • t03-q2b

      Tutorial_3_Questions.pdf

      analyseconceptual

      Q2 b) Special bits on a directory

      When applied to directories, these special bits have a slightly different meaning.

      • Create a directory named bertiesworld. Change its group ownership to bertie. Then set the appropriate directory bits so that any subdirectory or file created inside bertiesworld automatically inherits the group bertie.
      • In what scenarios could this behavior be useful?
      • Could this introduce any potential security risks?
      • setuid
      • unix-permissions
      Show worked solution
      1. Create the directory and set the group to bertie:
      mkdir bertiesworld
      ls -ltr
      drwxrwxr-x 2 ubuntu ubuntu 4096 Jul 30 12:02 bertiesworld
      
      sudo chown ubuntu:bertie bertiesworld/
      ls -ltr
      drwxrwxr-x 2 ubuntu bertie 4096 Jul 30 12:02 bertiesworld
      1. Create a test file inside the directory:
      cd bertiesworld/
      touch test_file.txt
      ls -ltr
      -rw-rw-r-- 1 ubuntu ubuntu 0 Jul 30 12:04 test_file.txt

      Note: the group is still ubuntu, not bertie.

      1. Set the setgid bit on the directory:
      cd ../
      sudo chmod g+s bertiesworld/
      ls -ltr
      drwxrwsr-x 2 ubuntu bertie 4096 Jul 30 12:06 bertiesworld

      Note: the s in the group execute position shows that the setgid bit is now set.

      1. Create another test file and check the group:
      cd bertiesworld/
      touch test_file_bertie_2.txt
      ls -ltr
      -rw-rw-r-- 1 ubuntu bertie 0 Jul 30 12:13 test_file_bertie_2.txt

      Now, all new files and subdirectories created inside bertiesworld automatically inherit the group bertie.

      When is this useful? This approach is useful when multiple users are collaborating and need shared group access to files and directories.

      Potential risk: it can become harder to track who has access if group memberships are not updated regularly. For example, a user who was removed from the project might still belong to the group and retain access.

      Cross-reference: Unix and Linux permissions.

    • t03-q2c

      Tutorial_3_Questions.pdf

      analyseconceptual

      Q2 c) Executables with setuid

      • Why do some programs require the setuid bit?
      • Are there any programs in your /usr/bin directory that have the setuid bit set and are owned by root? (Hint: you can use the find command with the -perm flag.)
      • setuid
      • privilege-escalation
      Show worked solution

      Some programs need to run with elevated (superuser) privileges even when the user running them does not have superuser access. The setuid bit allows these executables to run with the permissions of the file’s owner (often root), which is required for tasks such as changing passwords or mounting filesystems.

      To find all executables in /usr/bin that have the setuid bit set and are owned by root, you can run:

      find /usr/bin -user root -perm -4000 -exec ls -ldb {} \; > /tmp/filename

      Example output:

      -rwsr-xr-x 1 root root  39144 Mar  7  2020 /usr/bin/fusermount
      -rwsr-xr-x 1 root root  85064 Feb  6 2024 /usr/bin/chfn
      -rwsr-xr-x 1 root root  31032 Feb 21 2022 /usr/bin/pkexec
      -rwsr-xr-x 1 root root  68208 Feb  6 2024 /usr/bin/passwd
      -rwsr-xr-x 1 root root  88464 Feb  6 2024 /usr/bin/gpasswd
      -rwsr-xr-x 1 root root  44784 Feb  6 2024 /usr/bin/newgrp
      -rwsr-xr-x 1 root root  39144 Apr  9 2024 /usr/bin/umount
      -rwsr-xr-x 1 root root  67816 Apr  9 2024 /usr/bin/su
      -rwsr-xr-x 1 root root  53040 Feb  6 2024 /usr/bin/chsh
      -rwsr-xr-x 1 root root  55528 Apr  9 2024 /usr/bin/mount
      -rwsr-xr-x 1 root root 166056 Apr  4 2023 /usr/bin/sudo

      Cross-reference: Unix and Linux permissions.

    • t03-q3

      Tutorial_3_Questions.pdf

      analyseconceptual

      Q3: Real, effective, and saved UIDs in practice

      In the Tutorial 3 folder, you will find a C program named whoami3.c.

      • Inspect the code. Open whoami3.c and read through it. What does it do?
      • As user ubuntu, compile the program: gcc whoami3.c -o whoami3
      • As the user ubuntu, make it executable: chmod +x whoami3
      • Run the program: ./whoami3
      • What do you see? Explain your observation (look closely at the Real, Effective, and Saved UID values).
      • Now change the program’s ownership to root and set the SUID bit:
      sudo chown root:root whoami3
      sudo chmod u+s whoami3
      • Run ls -l whoami3 and note what has changed in the permission bits.
      • Now run the program again, as user ubuntu: ./whoami3
      • What do you see? Explain your observation.
        • How do the Real, Effective, and Saved UIDs compare to the previous run?
        • Why did some values change and others didn’t?
        • What does this tell you about how SUID affects process privileges?
      • uids
      • setuid
      Show worked solution

      What does the code do? The program calls getresuid() to retrieve the calling process’s Real, Effective, and Saved UIDs, then prints all three. It doesn’t modify anything — it’s purely observational, letting us see how the OS tracks these three separate identities for every process.

      Worked example

      Show answer and steps

      AnswerReal: 1000 Effective: 1000 Saved: 1000

      1. Before the SUID bit is set, whoami3 is an ordinary executable owned by ubuntu (UID 1000).
      2. The kernel launches it directly on behalf of ubuntu, so it sets Real = Effective = Saved = the launching user’s UID.
      3. All three UIDs come out identical and equal to 1000. There is no privilege distinction: the process can only do what ubuntu is allowed to do.

      After chown root:root and chmod u+s, the owner execute bit x becomes s (lowercase, since owner execute was already set). This is the SUID bit — it tells the kernel: “whenever this file is executed, set the process’s effective UID to the file owner’s UID (root), regardless of who runs it.”

      Worked example

      Show answer and steps

      AnswerReal: 1000 Effective: 0 Saved: 0

      1. Real UID stays 1000 (ubuntu) — the kernel always preserves who actually launched the process. This never changes just because SUID is set; it’s used for accounting, permission checks like “can this process signal that process,” and audit logging.
      2. Effective UID becomes 0 (root) — this is the direct effect of the SUID bit. The kernel sets the effective UID to match the file owner (root) at exec() time. All permission checks the kernel does from this point on (file access, etc.) use the effective UID, not the real one, so the process now has root-level access even though ubuntu launched it.
      3. Saved UID also becomes 0 (root) — the kernel copies the new effective UID into the saved UID at exec() time. This exists so that if the program later temporarily drops privilege (e.g., seteuid(ruid) to act as ubuntu for safety), it can restore root privilege afterward via seteuid(suid) without needing to re-authenticate. This is exactly how programs like passwd briefly de-escalate and re-escalate privilege while writing to /etc/shadow.

      Key takeaway. SUID doesn’t change who ran the program (Real UID) — it changes what the program is allowed to do (Effective UID), with the Saved UID acting as a “memory” of the elevated privilege so it can be restored after a temporary drop. This is the mechanism that lets an unprivileged user run a small, trusted, root-owned program (like passwd) to perform a specific privileged action, without giving that user root access to everything else.

      Cross-reference: Unix and Linux permissions.

    • t03-q4

      Tutorial_3_Questions.pdf

      analyseconceptual

      Q4: Privilege escalation and fallback with saved UID

      In the Tutorial 3 folder, you will find a C program named whoami4.c. This program builds on whoami3.c — instead of just reading the UIDs once, it prints them, temporarily drops root privilege, prints them again, then restores root privilege using the saved UID and prints them a third time.

      • Inspect the code. Open whoami4.c and read through it. What does it do? What functions does it call, and what do you expect each one to change?
      • As user ubuntu, compile the program: gcc whoami4.c -o whoami4
      • Change the program’s ownership to root and set the SUID bit:
      sudo chown root:root whoami4
      sudo chmod u+s whoami4
      • As user ubuntu, run the program: ./whoami4
      • You should see three lines of output, labelled Start, Dropped, and Restored. For each line, record the Real, Effective, and Saved UID.
      • Explain your observations:
        • At Start, why is the Effective UID 0 even though ubuntu launched the program?
        • At Dropped, which UID changed, and which stayed the same? Why did we lose root privilege here?
        • At Restored, how did the program get root privilege back without asking for a password or re-running as root?
        • If the Saved UID did not exist, would this “drop then restore” pattern still be possible? Why or why not?
        • Real-world connection: the passwd command uses exactly this pattern — briefly dropping to your real privilege level, then restoring root privilege only when it needs to write to /etc/shadow. Why might a program want to minimise the time it spends running with full root privilege, rather than just keeping it for the whole execution?
      • uids
      • privilege-escalation
      • setuid
      Show worked solution

      What does the code do? The program calls getresuid() three times, at different points in execution, to show how the Real, Effective, and Saved UIDs change as the process deliberately drops and then restores its privilege. First it prints the UIDs as soon as the program starts (Start). Then it calls seteuid(ruid) to temporarily drop its effective privilege down to the real (unprivileged) user and prints the UIDs again (Dropped). Finally it calls seteuid(suid) to restore its effective privilege back to root using the saved UID, and prints the UIDs a third time (Restored).

      Worked example

      Show answer and steps

      AnswerStart -> Real: 1000 Effective: 0 Saved: 0

      1. At Start, the Effective UID is already 0 (root), even though ubuntu (UID 1000) launched the program.
      2. This is the same SUID mechanism from the previous task — the kernel sets the effective UID to the file owner’s UID (root) at exec() time, regardless of who ran the file.
      3. The Saved UID is also 0, copied from the effective UID at the same moment.

      Worked example

      Show answer and steps

      AnswerDropped -> Real: 1000 Effective: 1000 Saved: 0

      1. At Dropped, only the Effective UID changes, from 0 back to 1000.
      2. The Real UID was never root to begin with, so it’s unaffected.
      3. Crucially, the Saved UID stays 0 — seteuid() only changes the effective UID, it does not touch the saved UID.
      4. At this point the process is voluntarily running with the same restricted privilege as ubuntu, even though it’s still technically the same SUID-root process. This is a deliberate safety measure: while performing routine, non-privileged work, the program avoids holding root power it doesn’t currently need.

      Worked example

      Show answer and steps

      AnswerRestored -> Real: 1000 Effective: 0 Saved: 0

      1. At Restored, the Effective UID jumps back to 0.
      2. This works because seteuid(suid) is allowed to set the effective UID to any value that matches the real, effective, or saved UID — and the saved UID was still 0 from the very first exec().
      3. No password, no re-authentication, and no call back into sudo was needed. The kernel already “remembered” that this process was entitled to root privilege, via the saved UID.

      If the Saved UID did not exist, this pattern would be impossible. Once the process dropped its effective UID to 1000, it would have no way to prove it was ever allowed to be root again — it would need to be re-executed from a SUID-root binary from scratch. The saved UID is what makes a reversible drop possible, as opposed to a permanent one.

      Real-world connection. passwd follows exactly this drop-then-restore pattern. It runs as SUID root, drops privilege while doing routine work like reading input or checking your current password, and only restores root privilege for the brief window where it actually needs to write to /etc/shadow. Minimising the time spent at full privilege reduces the “attack window” — if the program crashes, is exploited via a bug, or handles malicious input, it does so with the least privilege necessary for as much of its execution as possible. This is the Principle of Least Privilege applied at the level of a single process’s lifetime, not just at the level of user accounts.

      Key takeaway. seteuid() moves privilege between the Real, Effective, and Saved UIDs without discarding any of them — unlike setuid(), which collapses all three to the same value and permanently gives up the ability to restore a higher privilege. This distinction is exactly why security-sensitive SUID programs use seteuid() for temporary privilege changes, and reserve setuid() only for the point where they want to drop privilege for good.

      Cross-reference: Unix and Linux permissions.

    • t04-q1

      Tutorial_4_Questions.pdf

      analysedesign

      Q1: Revisiting simple encryption

      You are given a text file named enc.txt by a friend. They say they have no idea what it means — after all, they’ve never taken a class in cryptography (and they didn’t enjoy history much in school either).

      They watch you in wonder and awe as you begin decrypting it using Python, without relying on any cryptography libraries.

      Your task is to decrypt the given file enc.txt.

      Recall: this is a ciphertext-only attack scenario, where you are given only the encrypted message (ciphertext) and no information about the plaintext or the key. Your job is to analyze the ciphertext and deduce the plaintext through cryptanalysis techniques.

      a) Observe the contents of the given file

      Write code that prints the contents of the file.

      file =     # TODO: Open the enc.txt file
      
      content =  # TODO: Read the contents
      
      # TODO: Print the contents
      
      # Close the file

      b) Check the properties of the ciphertext

      That doesn’t reveal much, does it? Let’s examine some properties of the ciphertext:

      • Check the length of the ciphertext.
      • Find the factors of its length (use the factorint function in sympy).
      • Which numbers divide the length?
      from sympy.ntheory import factorint
      
      ## TODO print the total length of the content
      ## TODO use the factorint function to find the prime factors of content length

      Still not much insight. Let’s perform some alphabet/symbol analysis:

      Generate frequency plots assuming symbol lengths from 1 to 5. Write the code in a generic way:

      • Allow input of the symbol length to consider.
      • The code should progressively identify symbols, store them in a dictionary, and track each symbol’s frequency.
      • Once the dictionary is fully built, plot the frequency histogram of the symbols.
      • Based on the plots, which symbol length do you think is the correct one?
      ## TODO: Write a function to build the symbol frequency dictionary
      ## TODO: It will take the filename and the symbol length as inputs
      
      def build_symbol_dictionary(filename, symbol_length):
      
          file = ## TODO: Open the given file
      
          count = ## TODO: Build an empty dictionary
      
          symbol = ""                              ## Placeholder for the symbols - no need
      
          while True:
                 # TODO: Read the file by symbol_length
                 symbol =
      
          if not symbol:                           ## TODO: If there is no symbol, it means
      
          else:
                 if symbol in count: ## TODO: If the current symbol is already
      
          else:                                    ## TODO: Else, add the symbol to the dictionary
      
      symbol_frequency = build_symbol_dictionary("enc.txt", 3)
      
      print(symbol_frequency.keys())
      print(sum(symbol_frequency.values()))
      
      import matplotlib.pyplot as plt
      
      plt.bar(list(symbol_frequency.keys()), symbol_frequency.values(), color='b')
      plt.xticks(rotation = 45, size =6)
      plt.xlabel("Symbol")
      plt.ylabel("Frequency")
      plt.show()

      c) Decide on the symbol length

      From the above analysis decide on the symbol length. Now we need to try some substitutions.

      • What symbol can be the whitespace?
      • What symbol can be the letter e?
      • Write code to try out a few substitutions and see what makes sense. Try several runs with different guesses.
      file = open("enc.txt", 'r')
      
      content=file.read()
      sub_content=""
      
      for i in range(0,len(content),3):
             symbol = content[i:i+3]
             if symbol== ##TODO Experiment with guessing some symbols. You can add
                    symbol=
             if symbol== ##TODO Experiment with guessing some symbols. You can add
                    symbol=
             sub_content = sub_content+symbol
      
      print(sub_content)
      
      file.close()

      Hopefully by now you have identified some correct mappings. You can continue this process to find all the mappings, but it can be a bit tedious. Let’s see if we can identify a pattern:

      • Build a new sorted dictionary.
      • Replot the symbol histogram (this time sorting the keys).
      keys = list(symbol_frequency.keys())
      keys.sort()
      sorted_dict = {i: symbol_frequency[i] for i in keys}
      
      import matplotlib.pyplot as plt
      
      plt.bar(list(sorted_dict.keys()), sorted_dict.values(), color='b')
      plt.xticks(rotation = 45, size =6)
      plt.xlabel("Symbol")
      plt.ylabel("Frequency")
      plt.show()

      Based on this graph and the substitutions you found earlier, you can now express the mapping as a formula.

      • What is the equation for the mapping?

      d) Write code to decipher the full text

      import string
      
      chars = list(string.ascii_lowercase)
      
      file = open("enc.txt", 'r')
      
      content = file.read()
      file.close()
      
      plain_content = ""
      
      for i in range(0, len(content), 3):
             symbol = content[i:i+3]
             if symbol != # TODO: Write the program logic for non-whitespace char
      
             else:
                    plain_content += " "
      
      print(plain_content)
      
      with open("plain.txt", "w") as text_file:
             n = text_file.write(plain_content)
      • symmetric-crypto
      Show worked solution

      a) Observe the contents of the given file

      file = open("enc.txt")                   # TODO: Open the enc.txt file
      content = file.read()                    # TODO: Read the contents
      print(content)                           # TODO: Print the contents
      file.close()                             # Close the file

      b) Check the properties of the ciphertext

      from sympy.ntheory import factorint
      
      print(len(content)) ## TODO print the total length of the content
      factorint(len(content)) ## TODO use the factorint function to find the prime factors of content

      Output:

      9210
      {2: 1, 3: 1, 5: 1, 307: 1}

      Generating the symbol frequency dictionary:

      def build_symbol_dictionary(filename, symbol_length):
      
          file = open(filename, 'r') ## TODO: Open the given file
      
          count = {}                               ## TODO: Build an empty dictionary
      
          symbol = ""                              ## Placeholder for the symbols - no need
      
          while True:
                 # TODO: Read the file by symbol_length
                 symbol = file.read(symbol_length)
      
                 if not symbol:                           ## TODO: If there is no symbol, it means
                     file.close()
                     return count
      
                 else:
                     if symbol in count: ## TODO: If the current symbol is already
                         count[symbol] += 1
                     else:                                    ## TODO: Else, add the symbol to the dictionary
                         count[symbol] = 1
      
      symbol_frequency = build_symbol_dictionary("enc.txt", 3)
      
      print(symbol_frequency.keys())
      print(sum(symbol_frequency.values()))
      
      import matplotlib.pyplot as plt
      
      plt.bar(list(symbol_frequency.keys()), symbol_frequency.values(), color='b')
      plt.xticks(rotation = 45, size =6)
      plt.xlabel("Symbol")
      plt.ylabel("Frequency")
      plt.show()

      Output:

      dict_keys(['130', '118', '115', '128', '137', '119', '129', '111', '124', '135', '125', '121', '113', '116', '122', '117', '133', '131', '114', '123', '126', '134', '127', '112', '132', '136', '120'])
      3070

      c) Decide on the symbol length

      file = open("enc.txt", 'r')
      content=file.read()
      
      sub_content=""
      
      for i in range(0,len(content),3):
             symbol = content[i:i+3]
             if symbol=="137": ##TODO Experiment with guessing some symbols. You can add
                    symbol=" "
             if symbol=="115": ##TODO Experiment with guessing some symbols. You can add
                    symbol="e"
             sub_content = sub_content+symbol
      
      print(sub_content)
      
      file.close()

      d) Write code to decipher the full text

      import string
      
      chars = list(string.ascii_lowercase)
      
      file = open("enc.txt", 'r')
      
      content = file.read()
      file.close()
      
      plain_content = ""
      
      for i in range(0, len(content), 3):
             symbol = content[i:i+3]
             if symbol != '137': # TODO: Write the program logic for non-whitespace char
                 new_symbol = int(symbol) - 111
                 new_symbol = chars[new_symbol]
                 plain_content += new_symbol
             else:
                 plain_content += " "
      
      print(plain_content)
      
      with open("plain.txt", "w") as text_file:
             n = text_file.write(plain_content)

      Output (the decrypted plaintext, the opening of Douglas Adams’s “The Hitchhiker’s Guide to the Galaxy” passage on flying):

      there is an art it says or rather a knack to flying the knack lies in learning how to throw yourself at the ground and miss pick a nice day the hitchhikers guide to the galaxy suggests and try it the first part is easy all it requires is simply the ability to throw yourself forward with all your weight and the willingness not to mind that its going to hurt that is its going to hurt if you fail to miss the ground most people fail to miss the ground and if they are really trying properly the likelihood is that they will fail to miss it fairly hard clearly it is the second part the missing which presents the difficulties one problem is that you have to miss the ground accidentally its no good deliberately intending to miss the ground because you wont you have to have your attention suddenly distracted by something else when youre halfway there so that you are no longer thinking about falling or about the ground or about how much its going to hurt if you fail to miss it it is notoriously difficult to prize your attention away from these three things during the split second you have at your disposal hence most peoples failure and their eventual disillusionment with this exhilarating and spectacular sport if however you are lucky enough to have your attention momentarily distracted at the crucial moment by say a gorgeous pair of legs or a bomb going off in your vicinty or by suddenly spotting an extremely rare species of beetle crawling along a nearby twig then in your astonishment you will miss the ground completely and remain bobbing just a few inches above it in what might seem to be a slightly foolish manner this is a moment for superb and delicate concentration bob and float float and bob ignore all consideration of your own weight simply let yourself waft higher do not listen to what anybody says to you at this point because they are unlikely to say anything helpful they are most likely to say something along the lines of good god you cant possibly be flying it is vitally important not to believe them or they will suddenly be right waft higher and higher try a few swoops gentle ones at first then drift above the treetops breathing regularly do not wave at anybody when you have done this a few times you will find the moment of distraction rapidly easier and easier to achieve you will then learn all sorts of things about how to control your flight your speed your maneuverability and the trick usually lies in not thinking too hard about whatever you want to do but just allowing it to happen as if it were going to anyway you will also learn about how to land properly which is something you will almost certainly screw up and screw up badly on your first attempt there are private clubs you can join which help you achieve the allimportant moment of distraction they hire people with surprising bodies or opinions to leap out from behind bushes and exhibit and or explain them at the critical moments few genuine hitchhikers will be able to afford to join these clubs but some may be able to get temporary employment at them

      Solution. The mapping can be expressed as:

      c=p+111c = p + 111

      where p=0p = 0 corresponds to 'a', p=1p = 1 to 'b', and so on. The value 137 represents the whitespace character.

      Revise: Substitution, transposition and frequency analysis.

    • t04-q2

      Tutorial_4_Questions.pdf

      applydesign

      Q2: Doing it right — encryption

      Once you have decrypted enc.txt, you decide to do it properly this time.

      • Write code to read the decoded text file and encrypt it using AES-CBC.
      • Use the pycrypto library (docs).
      • You might need to pad your data. Why?
      • Choose a 128-bit key length.
      • Generate an IV using Crypto.Random.
      • Print the output as a hex-encoded string.
      • Write the output as binary to text.aes.
      # from os import lseek # (Unused import)
      from Crypto.Cipher import AES
      from Crypto.Random import get_random_bytes
      from Crypto.Util.Padding import pad
      
      def AES_Encrypt(inFileName, outFileName):
             # TODO: Generate random 16-byte key and IV
             key =
             iv =
      
             cipher = AES.new(key, AES.MODE_CBC, iv)
      
             # TODO: Load the input file
             with open(inFileName, 'rb') as text_file:
      
                    plaintext =
      
             # TODO: Perform the encryption
             ciphertext =
      
             # TODO: Store the encrypted file
             with open(outFileName, "wb") as cipher_file:
      
                    cipher_file.write(ciphertext)
      
             # TODO: Return the key and initialization vector (needed for decrypti
             return key, iv
      
      key, iv = AES_Encrypt("plain.txt", "testing.enc")
      • symmetric-crypto
      • cbc
      Show worked solution
      # from os import lseek # (Unused import)
      from Crypto.Cipher import AES
      from Crypto.Random import get_random_bytes
      from Crypto.Util.Padding import pad
      
      def AES_Encrypt(inFileName, outFileName):
             # TODO: Generate random 16-byte key and IV
             key = get_random_bytes(16)
             iv = get_random_bytes(16)
      
             cipher = AES.new(key, AES.MODE_CBC, iv)
      
             # TODO: Load the input file
             with open(inFileName, 'rb') as text_file:
      
                    plaintext = text_file.read()
      
             # TODO: Perform the encryption
             ciphertext = cipher.encrypt(pad(plaintext, 16))
      
             # TODO: Store the encrypted file
             with open(outFileName, "wb") as cipher_file:
      
                    cipher_file.write(ciphertext)
      
             # TODO: Return the key and initialization vector (needed for decryption)
             return key, iv
      
      key, iv = AES_Encrypt("plain.txt", "testing.enc")

      Code is shown above with the TODO sections completed.

      Revise: Modes of operation.

    • t04-q3

      Tutorial_4_Questions.pdf

      applydesign

      Q3: Doing it right — decryption

      Write a code snippet to check whether you can decrypt the file you just encrypted.

      from Crypto.Util.Padding import unpad
      
      def AES_Decrypt(key, iv, inFileName):
      
             # TODO: Load the encrypted file
             # TODO: Perform the decryption
      
                 print(plaintext)
      
          AES_Decrypt(key, iv, "testing.enc")
      • symmetric-crypto
      • cbc
      Show worked solution
      from Crypto.Util.Padding import unpad
      
      def AES_Decrypt(key, iv, inFileName):
      
             # TODO: Load the encrypted file
             with open(inFileName, 'rb') as text_file:
      
                    ciphertext = text_file.read()
      
             # TODO: Perform the decryption
             cipher = AES.new(key, AES.MODE_CBC, iv)
             plaintext = unpad(cipher.decrypt(ciphertext), 16)
      
             print(plaintext)
      
      AES_Decrypt(key, iv, "testing.enc")

      Code is shown above with the TODO sections completed. Output:

      b'there is an art it says or rather a knack to flying the knack lies in learning how to throw yourself at the ground and miss pick a nice day the hitchhikers guide to the galaxy suggests and try it the first part is easy all it requires is simply the ability to throw yourself forward with all your weight and the willingness not to mind that its going to hurt that is its going to hurt if you fail to miss the ground most people fail to miss the ground and if they are really trying properly the likelihood is that they will fail to miss it fairly hard clearly it is the second part the missing which presents the difficulties one problem is that you have to miss the ground accidentally its no good deliberately intending to miss the ground because you wont you have to have your attention suddenly distracted by something else when youre halfway there so that you are no longer thinking about falling or about the ground or about how much its going to hurt if you fail to miss it it is notoriously difficult to prize your attention away from these three things during the split second you have at your disposal hence most peoples failure and their eventual disillusionment with this exhilarating and spectacular sport if however you are lucky enough to have your attention momentarily distracted at the crucial moment by say a gorgeous pair of legs or a bomb going off in your vicinty or by suddenly spotting an extremely rare species of beetle crawling along a nearby twig then in your astonishment you will miss the ground completely and remain bobbing just a few inches above it in what might seem to be a slightly foolish manner this is a moment for superb and delicate concentration bob and float float and bob ignore all consideration of your own weight simply let yourself waft higher do not listen to what anybody says to you at this point because they are unlikely to say anything helpful they are most likely to say something along the lines of good god you cant possibly be flying it is vitally important not to believe them or they will suddenly be right waft higher and higher try a few swoops gentle ones at first then drift above the treetops breathing regularly do not wave at anybody when you have done this a few times you will find the moment of distraction rapidly easier and easier to achieve you will then learn all sorts of things about how to control your flight your speed your maneuverability and the trick usually lies in not thinking too hard about whatever you want to do but just allowing it to happen as if it were going to anyway you will also learn about how to land properly which is something you will almost certainly screw up and screw up badly on your first attempt there are private clubs you can join which help you achieve the allimportant moment of distraction they hire people with surprising bodies or opinions to leap out from behind bushes and exhibit and or explain them at the critical moments few genuine hitchhikers will be able to afford to join these clubs but some may be able to get temporary employment at them'

      Revise: Modes of operation.

    • t04-q4

      Tutorial_4_Questions.pdf

      analyseconceptual

      Q4: Ciphertext tampering in CBC mode

      AES in CBC (Cipher Block Chaining) mode links each ciphertext block to the previous one. See the given figure below.

      The figure did not survive extraction from the source PDF.

      Now consider the following:

      You have a ciphertext encrypted using AES-CBC. One byte of a ciphertext block is corrupted (e.g., flipped or modified).

      Questions:

      1. What will happen to the decryption of the corrupted block?
      2. What will happen to the next block during decryption?
      3. Will the remaining blocks (after the next one) decrypt correctly or incorrectly?

      Why?

      • block-modes
      • cbc
      Show worked solution

      1. Decryption of the corrupted block:

      The corrupted ciphertext block will decrypt to garbage because the corrupted byte causes the entire decrypted block to become invalid and appear as random noise.

      2. Effect on the next block during decryption:

      The next plaintext block will have exactly one byte corrupted at the same position as the corrupted ciphertext byte, due to the XOR operation with the corrupted ciphertext block. The rest of the bytes in the next plaintext block will decrypt correctly.

      3. Remaining blocks after the next one:

      All subsequent plaintext blocks will decrypt correctly since they depend on uncorrupted ciphertext blocks beyond the corrupted one.

      Revise: Modes of operation.

    • t05-q1a

      Tutorial_5_Questions.pdf

      applynumeric

      Q1: Number of Keys

      Let’s examine the number of keys required in a cryptosystem.

      a) Symmetric Case

      Assume there are n users in a fully decentralized (mesh) system. How many symmetric keys are needed to ensure confidentiality between all participants?

      • key-distribution
      Show worked solution

      If you want confidentiality between all participants, then every user must share a key with every other user. Since the keys are symmetric, this results in:

      n(n−1)/2 keysn(n - 1) / 2 \text{ keys}

      Revise: The key distribution problem.

    • t05-q1b

      Tutorial_5_Questions.pdf

      applynumeric

      Q1: Number of Keys

      Let’s examine the number of keys required in a cryptosystem.

      b) Asymmetric Case

      If public-key cryptography is used for encryption instead of symmetric cryptography, how many keys are required when there are n users in the system?

      • key-distribution
      • public-key-cryptography
      Show worked solution

      In public-key cryptography, every user has a public key (which everyone else can know and use) and one private key (kept secret). Therefore, the system requires:

      2n keys2n \text{ keys}

      Revise: The key distribution problem.

    • t05-q2

      Tutorial_5_Questions.pdf

      applycommand

      Q2: SSH Keys

      Currently, you log in to the VM using a username and password. In this task, we will create a new user on the VM, generate a new private and public key pair, and test logging into the machine using the keys.

      a) Set up port forwarding in VirtualBox

      You can add the port forwarding rule without shutting down the VM. With the VM running:

      • In the VM window, go to Devices → Network → Network Settings…
      • Select Adapter 1 (should be attached to NAT) → click Advanced → Port Forwarding.
      • Add a new rule: Host Port 2222 → Guest Port 22, Host IP 127.0.0.1.
      • Click OK.

      b) Create a new user on your VirtualBox VM

      • Use the command: sudo adduser sec_user
      • Next, you will be prompted to enter a password. Use one that you will remember or note it down.
      • Then, it will ask for some information like Full Name, Room Number, etc. You can simply press Enter to leave these blank.
      • Now, switch to the newly created user by running: su sec_user
      • If successful, you should be logged in as the new user (i.e., your command prompt will look like sec_user@<hostname>:/home/ubuntu$). You will be asked to enter the password.
      • Create a hidden directory called .ssh in the sec_user’s home directory by running: mkdir ~/.ssh. Here, ~ is a shortcut to the user’s home directory (i.e., /home/sec_user/).
      • Verify that the hidden directory was created:
        • Navigate to the home directory using either cd ~/ or cd /home/sec_user
        • Run ls -ltr — you will not see the .ssh directory because normal ls options do not show hidden files or directories.
        • Next, run ls -lart — this will show the hidden .ssh directory.

      c) Generate a private and public key pair on your local machine (host)

      For example, on a Mac, you can do the following in the command line:

      mac_user@mac CSEC5616 % ssh-keygen -t rsa
      
      Generating public/private rsa key pair.
      
      Enter file in which to save the key
      (/Users/mac_user/.ssh/id_rsa):
      
      Enter passphrase (empty for no passphrase):
      
      Enter same passphrase again:
      
      Your identification has been saved in
      /Users/mac_user/.ssh/id_rsa
      
      Your public key has been saved in
      /Users/mac_user/.ssh/id_rsa.pub

      Note the following:

      • You will be asked to create a passphrase. This adds extra security to the key. You can leave it empty by pressing Enter.
      • The command creates two files: id_rsa, which is the private key, and id_rsa.pub, which is the public key.
      • These files are saved in a directory similar to before (i.e., /Users/mac_user/.ssh/).

      Windows follows a similar process as described here: phoenixnap.com/kb/generate-ssh-key-windows-10

      d) Copy your public key to the VM

      Since you’re connecting to 127.0.0.1 on a custom port (2222) instead of a normal hostname/IP on port 22, you need to tell ssh-copy-id (or your manual copy command) about the custom port:

      If ssh-copy-id is not available (e.g. on some Windows setups), you can copy the contents of id_rsa.pub manually and append it to /home/sec_user/.ssh/authorized_keys on the VM. If there is no file called /home/sec_user/.ssh/authorized_keys in the VM, you can create one and add the public key.

      cat ~/.ssh/id_rsa.pub | ssh -p 2222 [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

      e) Test logging in using your key pair

      ssh -p 2222 [email protected]

      If everything is set up correctly, you should be logged in without being prompted for sec_user’s password (unless you set a passphrase on your key, in which case you’ll be asked for the passphrase instead).

      • public-key-cryptography
      • authentication
      Show worked solution

      Steps are as described in the questions above. Following these steps should allow you to successfully authenticate to the VM using SSH keys rather than passwords.

      Revise: Public-key cryptography and trapdoor functions.

    • t05-q3a

      Tutorial_5_Questions.pdf

      analyseconceptual

      Q3: Understanding SSH Authentication and Server Trust

      When you connect to a remote server using SSH with public key authentication, your private key on the client is used to prove your identity by responding to a challenge from the server.

      a) Explain why it is safe to share your public key with the server but not your private key.

      • authentication
      • public-key-cryptography
      Show worked solution

      It is safe to share your public key with the server because it is designed to be publicly known and cannot be used to derive your private key. The private key must remain secret because it is used to prove your identity; if it is exposed, anyone can impersonate you.

      Revise: Authentication protocols and challenge-response.

    • t05-q3b

      Tutorial_5_Questions.pdf

      analyseconceptual

      Q3: Understanding SSH Authentication and Server Trust

      b) Consider the scenario where an attacker sets up a fake server impersonating the legitimate server. Discuss what risks this poses to the client during the SSH connection.

      • person-in-the-middle
      • authentication
      Show worked solution

      If an attacker sets up a fake server impersonating the legitimate server, the client may unknowingly connect to it and send authentication information. This can lead to a man-in-the-middle (MITM) attack, where the attacker intercepts or captures sensitive information, potentially compromising the client’s credentials.

      Revise: Authentication protocols and challenge-response.

    • t05-q3c

      Tutorial_5_Questions.pdf

      analyseconceptual

      Q3: Understanding SSH Authentication and Server Trust

      c) Describe how the SSH client can protect itself from connecting to an impersonating (malicious) server.

      • authentication
      • person-in-the-middle
      Show worked solution

      The SSH client protects itself by verifying the server’s identity through the server’s host key, which is a cryptographic public/private key pair generated and stored on the server. The server keeps its private host key secret and shares its public host key with clients during connection. The client stores known server public host keys locally (in the known_hosts file) and checks if the received public key matches the stored one. If it matches, the client can be confident it is connecting to the legitimate server and not an impersonator.

      Revise: Authentication protocols and challenge-response.

    • t05-q3d

      Tutorial_5_Questions.pdf

      analyseconceptual

      Q3: Understanding SSH Authentication and Server Trust

      d) What could happen if the client ignores warnings about changes in the server’s identity (e.g., “REMOTE HOST IDENTIFICATION HAS CHANGED”)?

      • person-in-the-middle
      • authentication
      Show worked solution

      Ignoring warnings about changes in the server’s identity (e.g., “REMOTE HOST IDENTIFICATION HAS CHANGED”) can expose the client to MITM attacks. The client may connect to a malicious server impersonating the legitimate one, risking credential theft or data interception.

      Revise: Authentication protocols and challenge-response.

    • t05-q3e

      Tutorial_5_Questions.pdf

      recallconceptual

      Q3: Understanding SSH Authentication and Server Trust

      Bonus: Suggest best practices users should follow to maintain secure SSH connections.

      • authentication
      Show worked solution
      • Always verify server host keys before trusting a new or changed server.
      • Do not ignore SSH warnings about host key changes.
      • Use strong, passphrase-protected private keys.
      • Regularly update and manage known hosts files.
      • Use additional security measures like two-factor authentication if possible.

      Revise: Authentication protocols and challenge-response.

    • t05-q4

      Tutorial_5_Questions.pdf

      recallnumeric

      Q4: Textbook RSA

      Here, we will perform a simple RSA calculation by hand and, if needed, using a bit of programming. You are given the following RSA parameters:

      • n = 3127
      • e = 3
      • d = 2011
      • p = 53
      • q = 59

      a) Keys

      • What is the public key?
      • What is the private key?

      Note: The public key is composed of (e, n) and the private key is composed of (d, n).

      • rsa
      • key-generation
      Show worked solution

      Public Key: (3, 3127)

      Private Key: (2011, 3127)

      Revise: RSA.

    • t05-q5

      Tutorial_5_Questions.pdf

      applynumeric

      Q5: Euler’s Totient Function and Co-Primality

      Euler derived a neat formula to compute the number of integers that are co-prime to a given integer (n):

      φ(n)=n∏(1−1/i), where i∣n means the (distinct) prime divisors of n.\varphi(n) = n \prod (1 - 1/i), \text{ where } i|n \text{ means the (distinct) prime divisors of } n.

      a) Definition and examples

      • What is the definition of co-prime?
      • Write down all numbers to which 1 is co-prime.
      • Verify the validity of this equation using n = 8 and n = 15.
      • Using the above equation, show that φ(n) = (p - 1)(q - 1) when p, q are prime and n = pq.
      • euler-totient
      • number-theory
      Show worked solution

      What is the definition of co-prime?

      Two integers are coprime if the only positive integer that divides both is 1.

      Write down all numbers to which 1 is co-prime:

      That means 1 is coprime with all natural numbers greater than 1.

      Verify the validity of this equation using n = 8 and n = 15:

      Let’s take 8. The numbers less than 8 that are coprime to 8 are 1, 3, 5, and 7. That means φ(8) = 4.

      Now let’s verify this using the formula:

      φ(8)=8∏(1−1/i) for i∣8\varphi(8) = 8 \prod (1 - 1/i) \text{ for } i|8

      i∣8i|8 represents the distinct prime divisors of 8. That means it is only 2.

      φ(8)=8(1−1/2)=8⋅1/2=4\varphi(8) = 8(1 - 1/2) = 8 \cdot 1/2 = 4

      We have verified that the equation is correct.

      Similarly, let’s take 15. The numbers less than 15 that are coprime to 15 are 1, 2, 4, 7, 8, 11, 13, and 14. That means φ(15) = 8.

      Now let’s verify this using the formula:

      φ(15)=15∏(1−1/i) for i∣15\varphi(15) = 15 \prod (1 - 1/i) \text{ for } i|15

      i∣15i|15 represents the distinct prime divisors of 15. That means it is 3 and 5.

      φ(15)=15(1−1/3)(1−1/5)=15⋅2/3⋅4/5=8\varphi(15) = 15(1 - 1/3)(1 - 1/5) = 15 \cdot 2/3 \cdot 4/5 = 8

      Show that φ(n) = (p - 1)(q - 1) when p, q are prime and n = pq:

      The only prime numbers that divide n are, by definition, p and q. So we can write:

      φ(n)=n∏(1−1/i)=n(1−1/p)(1−1/q)\varphi(n) = n \prod (1 - 1/i) = n(1 - 1/p)(1 - 1/q)

      Since n = pq,

      φ(n)=pq(1−1/p)(1−1/q)=(p−1)(q−1)\varphi(n) = pq(1 - 1/p)(1 - 1/q) = (p - 1)(q - 1)

      Revise: Primes, Fermat, Euler and fast modular exponentiation.

    • t05-q6a

      Tutorial_5_Questions.pdf

      recallconceptual

      Q6: RSA Key Management

      a) Safekeeping

      Which information should be securely destroyed after generating the key?

      • rsa
      • key-generation
      Show worked solution

      p, q, and φ(n)

      Revise: RSA security and padding.

    • t05-q6b

      Tutorial_5_Questions.pdf

      applynumeric

      Q6: RSA Key Management

      b) Key length

      • Does this key pair look secure for use over the next five years?
      • What is the key length in bits?
      • rsa
      • key-generation
      Show worked solution

      Obviously, the prime numbers are not large enough, so the resulting key length is small.

      In Python, try bin(3127) which gives 110000110111; the length is only 12 bits!

      Revise: RSA security and padding.

    • t05-q7

      Tutorial_5_Questions.pdf

      applynumeric

      Q7: Manual RSA Encryption and Decryption

      Encrypt the letter A using the given RSA parameters. Note: ‘A’ corresponds to 65₁₀ in ASCII. Check your solution by decrypting it again.

      Given RSA parameters:

      • n = 3127
      • e = 3
      • d = 2011
      • rsa
      • modular-exponentiation
      Show worked solution

      Encryption:

      P = 65, e = 3, and n = 3127

      653 mod 3127=257665^3 \bmod 3127 = 2576

      Decryption:

      C = 2576, d = 2011, and n = 3127

      25762011 mod 3127=652576^{2011} \bmod 3127 = 65

      Revise: RSA.

    • t05-q8

      Tutorial_5_Questions.pdf

      applycommand

      Q8: Implementing RSA

      Next, we implement a simple version of RSA using Python. This is a basic version and is not secure for practical use. In practice, you must use established cryptographic libraries.

      • Most of the code is provided. You only need to complete a few parts.
      • Your tutor will guide you through the key ideas behind the code.
      • Complete the code as instructed.
      • Try a simple encryption and decryption.
      • Note that in some cases, this simple implementation may return the same value for both e and d. This is not recommended for real applications.
      import math
      import os
      import random
      
      MAX_LENGTH = 20 # bits
      
      ## TODO: Function for calculating the GCD using the Euclidean Algorithm
      def gcd(a, b):
      
          while b != 0:
              a, b = b, a % b
      
          return a
      
      # Function for EGCD
      # Returns (g, x, y) such that a*x + b*y = gcd(a, b)
      # Already completed
      def egcd(a, b):
      
          if a == 0:
              return (b, 0, 1)
      
          else:
              g, x, y = egcd(b % a, a)
              return (g, y - (b // a) * x, x)
      
      # Function to find the multiplicative inverse
      # Already completed
      def mulinv(b, n):
      
          g, x, _ = egcd(b, n)
          if g == 1:
      
              return x % n
          else:
      
              return -1
      
      # TODO - Complete the function to compute d when e and phi are known
      def compute_d(e, phi):
      
          d = -1
          while d < 0:
      
              d = mulinv(e, phi)
          return d
      
      def create_key():
          # We are sticking to two small prime numbers for demonstration. In real applications, use much larger primes.
          p=7
          q = 31
          phi = (p - 1) * (q - 1)
          e = random.randint(1, phi)
          g = gcd(e, phi)
          while g != 1:
              e = random.randint(1, phi)
              g = gcd(e, phi)
          d = compute_d(e, phi)
          return p, q, phi, e, d
      
      def encrypt(pub_key, plaintext):
          e, n = pub_key
          x = []
          for i in plaintext:
              if i.isupper():
                  m = ord(i) - 65
                  c = (m ** e) % n
                  x.append(c)
              elif i.islower():
                  m = ord(i) - 97
                  c = (m ** e) % n
                  x.append(c)
              elif i.isspace():
                  x.append(400)
          return x
      
      def decrypt(priv_key, ciphertext):
          d, n = priv_key
          x = ''
          for i in ciphertext:
              if i == 400:
                  x += ' '
              else:
                  m = (i ** d) % n
                  m += 65
                  c = chr(m)
                  x += c
          return x
      
      ## TODO - Do the following inside the main function:
      ## create the key
      ## print the RSA parameters
      ## encrypt and decrypt a simple text using the two functions.
      
      def main():
          p, q, phi, e, d = create_key()
          print("p =", p)
          print("q =", q)
          print("phi =", phi)
          print("e =", e)
          print("d =", d)
          name = "security"
          ciphertext = encrypt((e, p * q), name)
          print("Ciphertext:", ciphertext)
          plaintext = decrypt((d, p * q), ciphertext)
          print("Decrypted text:", plaintext)
      
      main()
      • rsa
      • key-generation
      Show worked solution

      Code is shown above with the TODO sections completed.

      Sample output:

      p=7
      q = 31
      phi = 180
      e = 169
      d = 49
      Ciphertext: [165, 39, 16, 195, 24, 190, 152, 17]
      Decrypted text: SECURITY

      Revise: RSA.

    • t06-q1

      Tutorial_6_Questions.pdf

      analyseconceptual

      Q1: CRC and Its Suitability for Message Authentication

      What is CRC?

      Cyclic Redundancy Check (CRC) is a widely used error-detection technique in digital communication and storage. It treats the message as a polynomial over a finite field, divides it by a fixed generator polynomial, and appends the remainder to the message. The receiver performs the same division to verify data integrity.

      This use of polynomial arithmetic may remind you of operations in AES, where multiplication in the finite field GF(2) is also defined using polynomials. In AES, however, the focus is on defining field multiplication rules for cryptographic transformations (e.g., MixColumns), not on detecting accidental errors. While both involve polynomials over finite fields, CRC is linear and lacks cryptographic strength, making it unsuitable for authentication purposes.

      Tasks

      • Is CRC a suitable function to be used in a MAC? Why or why not?
      • Consider how CRC works and whether it offers security against intentional manipulation.

      Research Task — MD5

      • Why is the MD5 hash algorithm no longer considered secure?
      • What essential property of cryptographic hash functions does it fail to uphold?

      Research Task — SHA-1

      • Why is SHA-1 being phased out?
      • Is it still safe to use today? What are the potential risks?
      • hash-functions
      • message-authentication-codes
      Show worked solution

      Is CRC a suitable function to be used in a MAC?

      No. CRC is good at detecting accidental changes in data, but it is not designed to resist deliberate tampering. CRC is linear and predictable, so an attacker can change the input and compute a valid CRC without knowing any secret key. It therefore lacks the collision resistance and unpredictability a secure MAC needs.

      Why is MD5 no longer used? What property of hash functions does it violate?

      MD5 is vulnerable to collision attacks: different inputs can produce the same hash value. This violates collision resistance, which is essential for a cryptographic hash function. The weakness makes MD5 unsuitable for applications such as digital signatures and message integrity.

      Why is SHA-1 being phased out? Is it still safe to use?

      Researchers have demonstrated practical collision attacks against SHA-1. The “SHAttered” attack by Google and CWI Amsterdam in 2017 showed that it is feasible to generate two different inputs that produce the same SHA-1 hash. This undermines the integrity of any system that relies on SHA-1 (see shattered.io).

      It may still appear in legacy systems, but it is considered risky and should be replaced with a stronger algorithm such as SHA-256 or SHA-3.

      Revise: Hash functions and what they are for.

    • t06-q2a

      Tutorial_6_Questions.pdf

      applycommand

      Q2: Understanding Hashing Methods

      Next, we will perform some basic tasks to explore common hashing methods. The most widely used hashing methods include:

      • MD5 (128-bit)
      • SHA-1 (160-bit)
      • SHA-256 (256-bit)
      • SHA-3 (256-bit)
      • bcrypt (192-bit)
      • PBKDF2 (256-bit)

      Recall from our previous tutorials that, some methods like bcrypt, scrypt, and PBKDF2 incorporate a configurable number of rounds or iterations, which slows down the hashing process. This intentional slowdown significantly reduces the hashing rate, making brute-force or dictionary attacks more difficult — an important feature for securely storing passwords.

      a) Matching MD5 Hashes

      Match each MD5 hash signature to its corresponding word from the list: “Sydney”, “Melbourne”, “Brisbane”, “Hobart”, “Darwin”, and “Perth”.

      • i) a4bd01593487c956f68d360c18cb68b3
      • ii) 1fc91e86962825bb745de53d1657b3e4
      • iii) 759302fb84c5f72078746e7358ba44a0
      • iv) 4bc44fa25c7afaf63618e6586084052e
      • v) 9f610f074be03799cf1727a85127ab55
      • vi) 7c885b9c7c703a77befcabeea54944d5
      from hashlib import md5
      
      for i in {"Sydney", "Melbourne", "Brisbane", "Hobart", "Darwin","Perth"}:
          ### TODO: Print the string and its MD5 hash as a hexadecimal value.
          ### TODO: Remember to encode() the string before hashing, then use hexdigest()
      • hash-functions
      Show worked solution
      from hashlib import md5
      
      for i in {"Sydney", "Melbourne", "Brisbane", "Hobart", "Darwin","Perth"}:
          print(i,md5(i.encode()).hexdigest())
      
      # Output
      # Darwin a4bd01593487c956f68d360c18cb68b3
      # Melbourne 7c885b9c7c703a77befcabeea54944d5
      # Perth 4bc44fa25c7afaf63618e6586084052e
      # Brisbane 759302fb84c5f72078746e7358ba44a0
      # Sydney 1fc91e86962825bb745de53d1657b3e4
      # Hobart 9f610f074be03799cf1727a85127ab55

      So the matches are:

      • i) a4bd01593487c956f68d360c18cb68b3 is Darwin
      • ii) 1fc91e86962825bb745de53d1657b3e4 is Sydney
      • iii) 759302fb84c5f72078746e7358ba44a0 is Brisbane
      • iv) 4bc44fa25c7afaf63618e6586084052e is Perth
      • v) 9f610f074be03799cf1727a85127ab55 is Hobart
      • vi) 7c885b9c7c703a77befcabeea54944d5 is Melbourne

      Revise: Hash functions and what they are for.

    • t06-q2b

      Tutorial_6_Questions.pdf

      applycommand

      Q2: Understanding Hashing Methods

      b) Generate MD5 Hashes Using OpenSSL

      OpenSSL is a useful tool for analyzing hashes and certificates. For more information, see: help.ubuntu.com/community/OpenSSL

      • Use the echo command together with OpenSSL to generate MD5 hashes for the given strings.
      • hash-functions
      Show worked solution
      $ echo -n 'Sydney' | openssl md5
      MD5(stdin)= 1fc91e86962825bb745de53d1657b3e4
      
      $ for var in Sydney Melbourne Brisbane Hobart Darwin Perth; do echo -n "$var" | openssl md5; done
      MD5(stdin)= 1fc91e86962825bb745de53d1657b3e4
      MD5(stdin)= 7c885b9c7c703a77befcabeea54944d5
      MD5(stdin)= 759302fb84c5f72078746e7358ba44a0
      MD5(stdin)= 9f610f074be03799cf1727a85127ab55
      MD5(stdin)= a4bd01593487c956f68d360c18cb68b3
      MD5(stdin)= 4bc44fa25c7afaf63618e6586084052e

      Revise: Hash functions and what they are for.

    • t06-q2c

      Tutorial_6_Questions.pdf

      applynumeric

      Q2: Understanding Hashing Methods

      c) Check the Hash Lengths

      • Determine the number of hexadecimal characters in the given hash signatures.
      • How does the number of hex characters relate to the length (in bits) of the hash?
      • Check the hash types: MD5, SHA-1, SHA-256, SHA-384, and SHA-512.
      from hashlib import md5
      from hashlib import sha1
      from hashlib import sha256
      from hashlib import sha384
      from hashlib import sha512
      
      plaintext = "Sydney"
      ## Print different hashes
      • hash-functions
      Show worked solution
      from hashlib import md5
      from hashlib import sha1
      from hashlib import sha256
      from hashlib import sha384
      from hashlib import sha512
      
      plaintext = "Sydney"
      print(plaintext,sha512(plaintext.encode()).hexdigest(), len(sha512(plaintext.encode()).hexdigest()))
      
      # Output
      # Sydney 0e0d9cdfe40a716fbef25e70be757c800bce3a82e082c842d58e066aa28c4f1b22011e738d83f8dd5a75cde05ba18c499c0ec2bf2729dc4f2b2bf57a35333bf4 128

      The released code shows the SHA-512 case. Its summary of all five:

      • MD5 produces 32 hex characters, corresponding to 128 bits
      • SHA-1 produces 40 hex characters, corresponding to 160 bits
      • SHA-256 produces 64 hex characters, corresponding to 256 bits
      • SHA-384 produces 96 hex characters, corresponding to 384 bits
      • SHA-512 produces 128 hex characters, corresponding to 512 bits
      • One hexadecimal character represents 4 bits.

      Revise: Hash functions and what they are for.

    • t06-q2d

      Tutorial_6_Questions.pdf

      applycommand

      Q2: Understanding Hashing Methods

      d) Identifying File Modifications Using Hashes

      You will find five files in the Tutorial_6 folder: a.txt to e.txt. The MD5 hashes of these files have been provided. Identify which file has been modified since the hashes were computed.

      • MD5(a.txt) = 47712f2371c49ed3f1b0086cf1ef16bb
      • MD5(b.txt) = eae6cb73251401f731306f79d7a6d7c6
      • MD5(c.txt) = 3dbaab35b18015be90c7cceb71a8b6a4
      • MD5(d.txt) = 418d6d2d7ccdfbf2bddffa7f91a1bcba
      • MD5(e.txt) = 3907aa1785f078dfd0b32b1e7d3ec78d

      You can use either openssl dgst -md5 <filename> or md5sum <filename> to compute the MD5 hash of a file.

      • hash-functions
      Show worked solution
      $ openssl dgst -md5 a.txt
      MD5(a.txt)= 47712f2371c49ed3f1b0086cf1ef16bb
      $ openssl dgst -md5 b.txt
      MD5(b.txt)= eae6cb73251401f731306f79d7a6d7c6
      $ openssl dgst -md5 c.txt
      MD5(c.txt)= 3dbaab35b18015be90c7cceb71a8b6a4
      $ openssl dgst -md5 d.txt
      MD5(d.txt)= 3f6788e675355ea33244910e01181fe8
      $ openssl dgst -md5 e.txt
      MD5(e.txt)= 3907aa1785f078dfd0b32b1e7d3ec78d

      File d.txt has been modified. Its hash is now 3f6788e675355ea33244910e01181fe8, not the supplied 418d6d2d7ccdfbf2bddffa7f91a1bcba. The other four match.

      Revise: Hash functions and what they are for.

    • t06-q3

      Tutorial_6_Questions.pdf

      applycommand

      Q3: HMAC

      HMAC (Hash-based Message Authentication Code) is a cryptographic technique used to ensure message integrity and authenticity. It combines a cryptographic hash function (like SHA-256) with a secret key to produce a fixed-size MAC (Message Authentication Code). This MAC verifies that:

      • The message has not been altered.
      • The sender knows the shared secret key.

      Note: HMAC does not provide confidentiality — it does not hide the message content.

      How HMAC Differs from AE and AEAD

      AE (Authenticated Encryption) ensures both confidentiality and authenticity of a message.

      • It encrypts the message and attaches a tag (like a MAC) to verify integrity.
      • Examples: AES-GCM, ChaCha20-Poly1305

      AEAD (Authenticated Encryption with Associated Data) extends AE by allowing parts of the data (called associated data) to remain unencrypted but still authenticated.

      • For example, metadata like packet headers can be authenticated without being encrypted.

      HMAC, in contrast:

      • Does not encrypt the message.
      • Provides authentication and integrity only, not confidentiality.
      • Can be used alongside encryption (e.g., encrypt-then-MAC) to form secure protocols.

      HMAC vs AE/AEAD

      FeatureHMACAE (e.g., AES-GCM)AEAD (e.g., ChaCha20-Poly1305)
      Integrity✓✓✓
      Authenticity✓✓✓
      Confidentiality✓✓
      Associated Data(authenticated but not encrypted)✓ (authenticated but not encrypted)

      Blueprint of HMAC

      Implement the HMAC scheme as a Python function hmac(k, m).

      • Use a block length of 256 bits (i.e., 32 bytes).
      • A fixed value is given for the key k.
      • Use SHA-2 (also called SHA-256) as the hash function.
      • Use 0x5c repeated 32 times as the outer padding (opad).
      • Use 0x36 repeated 32 times as the inner padding (ipad).

      Note: This is only a conceptual implementation to help you understand the ideas. Never use such a homemade HMAC in production. Finally, check if your result matches the HMAC generated by PyCryptodome.

      import random
      from hashlib import sha256
      from Crypto.Hash import HMAC as pycryptodome_hmac
      from Crypto.Hash import SHA256 as pycryptodome_sha256
      
      # The Block length for SHA256 is 512 bits, which is 64 bytes.
      BLOCK_LENGTH_BYTES = 64
      
      def hmac_custom(m, key):
          """
          Custom implementation of HMAC-SHA256.
      
          Args:
              m (str): The message to be hashed.
              key (str): The secret key.
      
          Returns:
              str: The hexadecimal representation of the HMAC value.
      
          """
      
          # 1. Convert key and message to bytes
          key_bytes = ## TODO
          m_bytes = ## TODO
      
          # 2. Key Handling:
          # If the key is longer than the block length, hash it first, so that
          if len(key_bytes) > BLOCK_LENGTH_BYTES:
      
              key_bytes = sha256(key_bytes).digest()
      
          # 3. Key Padding:
          # Pad the key with zeros to the block length.
          padded_key = ## TODO
      
          # 4. Define opad and ipad (as bytes)
          opad = ## TODO
          ipad = ## TODO
      
          # 5. XOR the padded key with opad and ipad
          okeypad = ## TODO
          ikeypad = ## TODO
      
          # 6. Apply the HMAC formula: H(okeypad || H(ikeypad || m))
          # Inner hash: H(ikeypad || m)
          inner_hash = sha256(ikeypad + m_bytes).digest()
      
          # Outer hash: H(okeypad || inner_hash)
          final_hmac = sha256(okeypad + inner_hash).hexdigest()
      
          return final_hmac
      
      # --- Verification ---
      
      # Sample data
      message = 'Security engineering is cool'
      secret_key = 'MySecretKey123'
      
      # Calculate HMAC using the custom function
      custom_hmac_value = hmac_custom(message, secret_key)
      print(f"Custom HMAC: {custom_hmac_value}")
      
      # Calculate HMAC using pycryptodome for verification
      # TODO
      
      # Verify that the values match
      if custom_hmac_value == pycryptodome_hmac_value:
      
          print("\nVerification successful: The custom HMAC matches the pycryptodome implementation.")
      else:
      
          print("\nVerification failed: The custom HMAC does not match.")
      • hmac
      • message-authentication-codes
      Show worked solution
      import random
      from hashlib import sha256
      from Crypto.Hash import HMAC as pycryptodome_hmac
      from Crypto.Hash import SHA256 as pycryptodome_sha256
      
      # The Block length for SHA256 is 512 bits, which is 64 bytes.
      BLOCK_LENGTH_BYTES = 64
      
      def hmac_custom(m, key):
          """
          Custom implementation of HMAC-SHA256.
      
          Args:
              m (str): The message to be hashed.
              key (str): The secret key.
      
          Returns:
              str: The hexadecimal representation of the HMAC value.
      
          """
      
          # 1. Convert key and message to bytes
          key_bytes = key.encode('utf-8')
          m_bytes = m.encode('utf-8')
      
          # 2. Key Handling:
          # If the key is longer than the block length, hash it first, so that
          if len(key_bytes) > BLOCK_LENGTH_BYTES:
      
              key_bytes = sha256(key_bytes).digest()
      
          # 3. Key Padding:
          # Pad the key with zeros to the block length.
          padded_key = key_bytes.ljust(BLOCK_LENGTH_BYTES, b'\x00')
      
          # 4. Define opad and ipad (as bytes)
          opad = b'\x5c' * BLOCK_LENGTH_BYTES
          ipad = b'\x36' * BLOCK_LENGTH_BYTES
      
          # 5. XOR the padded key with opad and ipad
          okeypad = bytes(a ^ b for a, b in zip(padded_key, opad))
          ikeypad = bytes(a ^ b for a, b in zip(padded_key, ipad))
      
          # 6. Apply the HMAC formula: H(okeypad || H(ikeypad || m))
          # Inner hash: H(ikeypad || m)
          inner_hash = sha256(ikeypad + m_bytes).digest()
      
          # Outer hash: H(okeypad || inner_hash)
          final_hmac = sha256(okeypad + inner_hash).hexdigest()
      
          return final_hmac
      
      # --- Verification ---
      
      # Sample data
      message = 'Security engineering is cool'
      secret_key = 'MySecretKey123'
      
      # Calculate HMAC using the custom function
      custom_hmac_value = hmac_custom(message, secret_key)
      print(f"Custom HMAC: {custom_hmac_value}")
      
      # Calculate HMAC using pycryptodome for verification
      pycryptodome_hmac_obj = pycryptodome_hmac.new(secret_key.encode('utf-8'),
      pycryptodome_hmac_obj.update(message.encode('utf-8'))
      pycryptodome_hmac_value = pycryptodome_hmac_obj.hexdigest()
      print(f"Pycryptodome: {pycryptodome_hmac_value}")
      
      # Verify that the values match
      if custom_hmac_value == pycryptodome_hmac_value:
      
          print("\nVerification successful: The custom HMAC matches the pycryptodome HMAC.")
      else:
      
          print("\nVerification failed: The custom HMAC does not match.")
      
      # Output
      # Custom HMAC: 01367a2812c570f88cb9e94b21bbaf96fe1986d7c7bf528913a3eb10f5ab4a45
      # Pycryptodome: 01367a2812c570f88cb9e94b21bbaf96fe1986d7c7bf528913a3eb10f5ab4a45
      #
      # Verification successful: The custom HMAC matches the pycryptodome HMAC.

      The pycryptodome_hmac.new(...) line is cut off in the released solution, so it is reproduced exactly as printed. The unit’s own text stops there.

      Revise: Message authentication codes and HMAC.

    • t06-q4

      Tutorial_6_Questions.pdf

      applycommand

      Q4: AE and AEAD in Practice

      As mentioned above, AE (Authenticated Encryption) and AEAD (Authenticated Encryption with Associated Data) ensure that encryption and message authentication happen together, rather than as separate steps. This design became necessary because, in the past, developers often misused or incorrectly combined separate encryption and MAC functions, leading to serious security flaws. AEAD addresses this by integrating both operations into a single, well-defined primitive.

      Today, AEAD is considered the state-of-the-art and is used in most modern communication protocols, including TLS (HTTPS), QUIC, and Signal. It reduces the chance of implementation errors, improves performance, and guarantees that both the confidentiality and integrity of the message are protected in a single operation.

      AEAD also supports associated data (like headers) that need to be authenticated but not encrypted — useful in protocols where some information must remain visible but still protected against tampering.

      Note: AES-GCM is a widely used AEAD mode that combines AES in counter mode for encryption with a MAC called GHASH, which is based on finite field multiplication. Unlike traditional MACs such as HMAC or CMAC (more on this later), GHASH is optimized for performance and parallelizability, making AES-GCM especially efficient in high-speed networking.

      Exercise: AES-GCM as AEAD with Integrity Verification

      Task: Complete the following Python code using PyCryptodome to:

      • Encrypt a plaintext message using AES-GCM.
      • Add Additional Authenticated Data (AAD) that will not be encrypted, but whose integrity is protected.
      • Print the ciphertext and the authentication tag (MAC).
      • Simulate tampering by modifying the ciphertext.
      • Attempt decryption and ensure that integrity verification fails when the ciphertext is altered.
      from Crypto.Cipher import AES
      from Crypto.Random import get_random_bytes
      
      # Step 1: Generate a key and nonce
      key = get_random_bytes(16) # AES-128
      nonce = get_random_bytes(12) # Recommended size for GCM
      
      data = b'This is a secret message.'
      aad = b'authenticated-data'
      
      # Step 2: Encrypt using AES-GCM
      cipher = ## TODO Define the cipher
      cipher # TODO Add AAD
      ciphertext, tag = # TODO Encrypt and get tag
      
      print("Ciphertext:", ciphertext.hex())
      print("Tag:", tag.hex())
      
      # Step 3: Modify the ciphertext (simulate tampering)
      tampered_ciphertext = bytearray(ciphertext)
      # TODO Flip a bit
      
      # Step 4: Try to decrypt and verify tag
      # TODO
      • authenticated-encryption
      • aead
      • gcm
      Show worked solution
      from Crypto.Cipher import AES
      from Crypto.Random import get_random_bytes
      
      # Step 1: Generate a key and nonce
      key = get_random_bytes(16) # AES-128
      nonce = get_random_bytes(12) # Recommended size for GCM
      
      data = b'This is a secret message.'
      aad = b'authenticated-data'
      
      # Step 2: Encrypt using AES-GCM
      cipher = AES.new(key, AES.MODE_GCM, nonce=nonce)
      cipher.update(aad) # Add AAD
      ciphertext, tag = cipher.encrypt_and_digest(data)
      
      print("Ciphertext:", ciphertext.hex())
      print("Tag:", tag.hex())
      
      # Step 3: Modify the ciphertext (simulate tampering)
      tampered_ciphertext = bytearray(ciphertext)
      tampered_ciphertext[0] ^= 0x01 # Flip a bit
      
      # Step 4: Try to decrypt and verify tag
      try:
      
          cipher_dec = AES.new(key, AES.MODE_GCM, nonce=nonce)
          cipher_dec.update(aad) # Add the same AAD
          plaintext = cipher_dec.decrypt_and_verify(tampered_ciphertext, tag)
          print("Plaintext:", plaintext)
      except ValueError:
      
          print("Integrity check failed -- ciphertext has been tampered with.")
      
      # Output
      # Ciphertext: a37f8055595109613553364e77d5b6750fb353e5f78278d684
      # Tag: b034bca99a3cd834d389191e0e8f9d5f
      # Integrity check failed -- ciphertext has been tampered with.

      Revise: Authenticated encryption, GCM and CCM.

    • t07-q1

      Tutorial_7_Questions.pdf

      applycommand

      Q1: Exploring Digital Certificates

      A digital certificate is a structured, signed document that binds a public key to a verified identity (such as a domain name or an organization). It follows the X.509 standard and is typically issued by a Certificate Authority (CA).

      FieldDescription
      SubjectThe identity being certified (e.g., domain)
      IssuerThe Certificate Authority (CA) that issued it
      Public KeyUsed to establish secure communication
      Validity PeriodStart and end time for certificate validity
      Serial NumberUnique identifier for the certificate
      SignatureCA’s cryptographic signature over the contents

      Note: Real certificates include additional fields (e.g., extensions, key usage, algorithms) that control behavior and compatibility across systems.

      Formats you will meet:

      • .pem: Base64-encoded certificate, used by OpenSSL, Apache, Nginx
      • .cer: can be PEM or DER (binary); used in Windows and Java environments
      • .crt: often identical to .pem; varies by convention

      a) Using OpenSSL

      OpenSSL is a command-line tool that can be used to display the contents of an X.509 certificate. We provide a certificate file: whoami.pem. Use openssl x509 -help to find out how to display the certificate in a human-readable format. Then, answer the following questions:

      • Who is the issuer? Look up the organization.
      • Who is the subject (i.e., the certified entity)?
      • What is the algorithm used for the public key?
      • What is the key length?
      • Are Certificate Revocation Lists (CRLs) defined?
      • Is Online Certificate Status Protocol (OCSP) defined?
      • What hash function is used for the signature?

      b) Let’s try one more: fred.cer

      Credit: Applied Crypto by Bill Buchanan

      Examine the certificate and find the following information:

      • Serial number
      • Effective date
      • Name (i.e., the Subject)
      • Issuer
      • What is the CN (Common Name) used for?
      • What is the OU (Organizational Unit) used for?
      • What is the O (Organization) used for?
      • What is the L (Locality) used for?

      Note: The fred.cer file is in DER (Distinguished Encoding Rules) format, a binary encoding often used with .cer extensions. This differs from the .pem format we examined earlier, which is a Base64-encoded version of the certificate wrapped with -----BEGIN CERTIFICATE----- and -----END CERTIFICATE----- markers.

      PEM is human-readable; DER is not. Tools like openssl can be used to decode .cer files for analysis.

      • certificates
      • x509
      Show worked solution

      a) whoami.pem

      $ openssl x509 -in whoami.pem -text -noout
      Certificate:
          Data:
              Version: 3 (0x2)
              Serial Number:
                  72:ea:64:de:cb:5f:12:bf:fe:29:04:ad:30:8b:dd:ca:9d:d9:e3:9e
              Signature Algorithm: sha256WithRSAEncryption
              Issuer: C=BM, O=QuoVadis Limited, CN=QuoVadis Global SSL ICA G3
              Validity
                  Not Before: Mar  9 05:53:39 2018 GMT
                  Not After : Mar  9 06:03:00 2020 GMT
              Subject: C=AU, ST=New South Wales, L=Sydney, O=The University of Sydney,
                       OU=Information and Communications Technology, CN=*.sydney.edu.au
              Subject Public Key Info:
                  Public Key Algorithm: rsaEncryption
                      Public-Key: (2048 bit)
                      ...
                      Exponent: 65537 (0x10001)
              X509v3 extensions:
                  ...
                  Authority Information Access:
                      CA Issuers - URI:http://trust.quovadisglobal.com/qvsslg3.crt
                      OCSP - URI:http://ocsp.quovadisglobal.com
                  ...
                  X509v3 CRL Distribution Points:
                      Full Name:
                        URI:http://crl.quovadisglobal.com/qvsslg3.crl
                  ...
          Signature Algorithm: sha256WithRSAEncryption

      The ... lines stand for the modulus, the Subject Alternative Name, the policy, key usage and Signed Certificate Timestamp entries and the signature value, which the unit’s output prints in full.

      • Issuer: QuoVadis Limited
      • Subject (the certified entity): The University of Sydney
      • Public key algorithm: RSA encryption
      • Key length: 2048 bits
      • CRLs defined: yes, a URL is given, http://crl.quovadisglobal.com/qvsslg3.crl
      • OCSP defined: yes, a URL is given, http://ocsp.quovadisglobal.com
      • Signature hash function: SHA-256

      b) fred.cer

      $ openssl x509 -in fred.cer -text -noout
      Certificate:
          Data:
              Version: 3 (0x2)
              Serial Number: 7350616 (0x702958)
              Signature Algorithm: sha1WithRSAEncryption
              Issuer: C=GB, ST=Lothian, L=Edinburgh, O=Nowhere, emailAddress=fred@home, OU=None, CN=Fred Smith
              Validity
                  Not Before: Apr 24 20:18:42 2008 GMT
                  Not After : Apr 24 20:18:42 2010 GMT
              Subject: C=GB, ST=Lothian, L=Edinburgh, O=Nowhere, emailAddress=fred@home, OU=None, CN=Fred Smith
              Subject Public Key Info:
                  Public Key Algorithm: rsaEncryption
                      Public-Key: (1024 bit)
                      ...
              X509v3 extensions:
                  Netscape SSL Server Name:
                      www.abylonsoft.de
          Signature Algorithm: sha1WithRSAEncryption
      • Serial number: 7350616
      • Effective date: Apr 24 20:18:42 2008 GMT
      • Name (the Subject): Fred Smith
      • Issuer: the released solution leaves this line blank. The output above prints it as the same string as the Subject, so the certificate is self-issued.
      • CN stands for Common Name
      • OU stands for Organisational Unit
      • O stands for Organisation
      • L stands for Location (the question sheet writes Locality)

      The solution ends with a link to a list of the various name attributes.

      Revise: Public-key certificates and X.509.

    • t07-q2

      Tutorial_7_Questions.pdf

      applycommand

      Q2: Exploring Digital Certificates in the Internet

      openssl can also be used to download and inspect certificates from a web server. The command openssl s_client -connect x.com:443 will display all certificates used by x.com.

      Run the tool to inspect the certificate configurations of the following organisations and answer the questions below:

      • Which Certificate Authorities (CAs) are used by microsoft.com, x.com, and my.gov.au?
        • Note: It is sufficient to inspect the first few lines of the output.
      • Are intermediate certificates used? Speculate why.
        • Note: Again, the first few lines of the output should be enough.

      Tip: After running the command, you may need to stop it manually using Ctrl+C (in the command line) or the Stop button if using a Jupyter notebook cell.

      • certificate-authority
      • certificate-chain
      Show worked solution

      The released solution says these answers may vary.

      Which CAs?

      • x.com: Let’s Encrypt
      • microsoft.com: Microsoft Azure RSA TLS Issuing CA 08
      • my.gov.au: Entrust OV

      To print the CA of a website’s certificate:

      $ openssl s_client -connect x.com:443 -showcerts </dev/null 2>/dev/null | openssl x509 -noout -issuer

      The first lines of the unit’s own s_client output for the three sites (taken on the day the notebook was run, so the names can differ from the list above):

      $ openssl s_client -connect x.com:443
      depth=2 C=US, O=Internet Security Research Group, CN=ISRG Root X1
      depth=1 C=US, O=Let's Encrypt, CN=E7
      depth=0 CN=x.com
      
      $ openssl s_client -connect microsoft.com:443
      depth=3 C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2
      depth=2 C=US, O=Microsoft Corporation, CN=Microsoft TLS RSA Root G2
      depth=1 C=US, O=Microsoft Corporation, CN=Microsoft TLS G2 RSA CA OCSP 04
      depth=0 C=US, ST=WA, L=Redmond, O=Microsoft Corporation, CN=microsoft.com
      
      $ openssl s_client -connect my.gov.au:443
      depth=2 C=US, O=DigiCert Inc, OU=www.digicert.com, CN=DigiCert Global Root G2
      depth=1 C=US, O=DigiCert Inc, CN=DigiCert Global G2 TLS RSA SHA256 2020 CA1
      depth=0 C=AU, ST=Australian Capital Territory, L=Greenway, O=Services Australia, CN=*.my.gov.au

      Are intermediate certificates used? Speculate why.

      Yes, and this is now enforced by standards. The main reason is to keep the main CA private key offline, and in day-to-day use, work with the intermediate certificate. This helps prevent the loss of the main private key in case of a CA compromise.

      For x.com there are multiple levels:

      • Level 0: leaf certificate issued to x.com
      • Level 1: intermediate certificate, Let’s Encrypt
      • Level 2: root certificate, ISRG Root X1

      Revise: Public key infrastructure and revocation.

    • t07-q3

      Tutorial_7_Questions.pdf

      analysecommand

      Q3: Issues in Certificates

      One possible cause of the infamous invalid certificate error is a mismatch between the domain name listed in the certificate and the actual domain name of the website.

      Using your browser, try to visit:

      • http://testfire.net/
      • https://testfire.net/

      (This is a test website maintained by IBM for demonstrating common web application vulnerabilities and website defects.)

      The first connection is not encrypted, so you will be able to visit the website without any issues. However, the second attempt uses encryption, and you will receive a certificate error: NET::ERR_CERT_COMMON_NAME_INVALID.

      a) Use openssl and try to find the problem

      b) Use SSL Labs to Verify Your Answer

      SSL Labs is a useful tool for troubleshooting SSL certificate issues. Try running a scan for https://testfire.net and review the results.

      Then, run a scan for another site such as www.sydney.edu.au for comparison.

      • certificates
      • tls
      Show worked solution

      a) openssl

      $ openssl s_client -connect testfire.net:443
      depth=2 C=US, ST=New Jersey, L=Jersey City, O=The USERTRUST Network, CN=USERTrust RSA Certification Authority
      verify return:1
      depth=1 C=GB, ST=Greater Manchester, L=Salford, O=Sectigo Limited, CN=Sectigo RSA Domain Validation Secure Server CA
      verify return:1
      depth=0 CN=demo.testfire.net
      verify error:num=10:certificate has expired
      notAfter=Jun 21 23:59:59 2026 GMT
      verify return:1
      ...
      Verification error: certificate has expired
      ...
      Verify return code: 10 (certificate has expired)

      The subject in the certificate is demo.testfire.net, which is different from testfire.net, the name we are trying to visit. Modern browsers do not allow such mismatches.

      The unit’s output also shows certificate has expired (error 10), a second fault in the same certificate. The released solution names only the name mismatch.

      b) SSL Labs

      SSL Labs complains about the same issue for testfire.net. The scan for www.sydney.edu.au may take some time, but it will not generate any errors.

      Revise: Public-key certificates and X.509.

    • t07-q4

      Tutorial_7_Questions.pdf

      applycommand

      Q4: Verifying the Certificate Chain of Trust with OpenSSL

      What is a certificate chain of trust?

      When you connect securely to a website (e.g., https://example.com), your browser or client needs to verify that the server’s TLS certificate is authentic and issued by a trusted authority.

      This verification does not happen in isolation. Instead, it relies on a chain of trust that connects the server’s certificate to a trusted root certificate authority (CA) that your system already knows about.

      The chain typically includes:

      1. Leaf certificate (server certificate): belongs to the website (e.g., x.com)
      2. Intermediate certificate(s): issued by a trusted root CA, used to sign the server certificate
      3. Root certificate: issued by a trusted Certificate Authority, pre-installed on your system

      If any certificate in the chain is missing or invalid, verification will fail.

      Using OpenSSL to verify the chain of trust

      We can use OpenSSL tools to manually inspect and verify the certificate chain returned by a server. We will:

      1. Fetch the full certificate chain from the server
      2. Extract the certificates
      3. Use OpenSSL’s verify command to validate the chain

      We will see this in action using the domain x.com.

      Use openssl to verify the chain of trust for x.com

      You will need to locate the root certificate store on your Ubuntu system.

      • certificate-chain
      • pki
      Show worked solution

      Connect to the server and retrieve the full certificate chain, pointing openssl at the system root store:

      openssl s_client -connect testfire.net:443 -CApath /etc/ssl/certs -showcerts

      For verified certificate chains you will see the output Verify return code: 0 (ok).

      Two things in the released solution do not line up with the question. The question asks about x.com, but the printed command connects to testfire.net. The solution also stops at this one command and does not show the extract-and-openssl verify steps the question lists.

      Revise: Public key infrastructure and revocation.

    • t07-q5

      Tutorial_7_Questions.pdf

      analyseconceptual

      Q5: Expired Certificates

      Since September 2020, major browser vendors such as Google, Apple, and Microsoft have enforced stricter rules regarding certificate validity. Publicly rooted digital certificates that expire more than 13 months (or 398 days) from their creation date are no longer accepted in modern web browsers. This marked a significant shift from earlier practices, where certificates were often valid for 8–10 years. The move was intended to enhance security across the web ecosystem.

      a) Explain how this policy improves the security of websites and users.

      b) What practical or usability challenges may have arisen during the early stages of this transition?

      • certificates
      • pki
      Show worked solution

      a) How the policy improves security

      • It reduces the possible exploitation window of compromised certificates.
      • It acts as a partial solution to the broken certificate revocation process.
      • It allows certificate owners to upgrade to stronger encryption algorithms and phase out weaker ones more frequently.

      b) Early challenges

      • Many organizations without automated certificate renewal mechanisms may face service outages.
      • Frequent certificate maintenance can become tedious, especially in IoT environments where there are a large number of distributed devices.

      Revise: Public key infrastructure and revocation.

    • t07-q6

      Tutorial_7_Questions.pdf

      recallconceptual

      Q6: Homework

      Please read about the following two concepts:

      • Self-Signed Certificates
      • SSL Proxies
      • certificates
      • pki
      Show worked solution

      Self-signed certificates

      A self-signed certificate is one that is not signed by any CA, neither private nor public. Instead, the certificate is signed with its own private key, rather than being issued by a public or private CA. Normally, a certificate’s subject public key is signed by the CA’s private key. In a self-signed certificate, the subject’s public key is signed by its own private key. Self-signed certificates are useful for testing and within internal networks.

      The solution links to further reading on self-signed certificate risks.

      SSL proxies

      SSL proxies use a form of Man-in-the-Middle (MITM) attack where the administering organization installs a trusted certificate on devices within their network.

      The solution links to further reading on SSL proxies and HTTPS filtering.

      Revise: Public-key certificates and X.509.

    • t08-q1

      Tutorial_8_Questions.pdf

      applycommand

      Section 1: Self-signed Digital Certificates

      In this tutorial, we will program a primitive TLS-based application. First, we will run a TLS server using OpenSSL and then write a Python client to interact with it.

      To run a TLS server, we will need a certificate. Recall that digital certificates are usually signed by trusted third parties such as Certificate Authorities (CAs). This allows us to verify whether the public key contained in the certificate belongs to the correct party. However, for experimentation, we cannot use these certificates since they must be purchased from a CA. Therefore, in development and lab settings, we use self-signed certificates.

      A self-signed certificate is a digital certificate issued by the person or entity creating the certificate rather than by a trusted third-party certificate authority. This means the certificate is not backed by a well-known and trusted third party, so it may not be considered as secure as a certificate issued by a trusted authority.

      Simply put, a self-signed certificate is neither privately nor publicly certified by a CA. Instead of seeking the certificate from a public or private CA, it is signed using its own private key; i.e., the signature in the certificate can be validated by the public key contained within the certificate itself.

      We have already created a certificate for you, certificate.crt, which is available in the tutorial folder. Use the openssl command you learned last week to inspect the certificate’s contents.

      • What is the public key algorithm used in the certificate?
      • What is the email address associated with the certificate?
      • What is the Common Name (CN)? We will need it later.
      • certificates
      • x509
      • tls
      Show worked solution
      $ openssl x509 -in ./certificate.crt -text -noout
      Certificate:
          Data:
              Version: 1 (0x0)
              Serial Number:
                  4a:b8:c9:37:9f:bb:52:34:06:96:25:48:5d:2a:f8:1a:d0:1f:ed:80
              Signature Algorithm: sha256WithRSAEncryption
              Issuer: C=AU, ST=NSW, L=Sydney, O=The University of Sydney, OU=The School of Computer Science, CN=localhost, [email protected]
              Validity
                  Not Before: Apr 19 01:39:46 2024 GMT
                  Not After : Oct 10 01:39:46 2029 GMT
              Subject: C=AU, ST=NSW, L=Sydney, O=The University of Sydney, OU=The School of Computer Science, CN=localhost, [email protected]
              Subject Public Key Info:
                  Public Key Algorithm: rsaEncryption
                      Public-Key: (2048 bit)
                      ...
                      Exponent: 65537 (0x10001)
          Signature Algorithm: sha256WithRSAEncryption

      The ... stands for the modulus and the signature value, which the unit’s output prints in full.

      The Issuer and Subject lines are identical, which is what makes the certificate self-signed.

      Revise: Public-key certificates and X.509.

    • t08-q2

      Tutorial_8_Questions.pdf

      applycommand

      Section 2: A Quick and Dirty TLS Server for Debugging Purposes

      The openssl s_server command allows you to run a TLS server on a specified port. This server will perform TLS handshakes as required and display anything the client sends. However, you need to pass a few arguments to make it work.

      • Open a new SSH connection to the VM.

      • Run the following OpenSSL command to start the server:

        sudo openssl s_server -accept 4443 -cert certificate.crt -key private.key
      • You will be prompted to enter the access code for the private key. Enter usyd.

      • If everything is running correctly, you will see the message Using default temp DH parameters ACCEPT in the command line.

      • If you get an error like Address already in use, try using a different port number.

      • Do not close this terminal window while the server is running.

      • tls
      • sockets

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: TLS: design rationale and the socket abstraction.

    • t08-q3

      Tutorial_8_Questions.pdf

      applycommand

      Section 3: Complete the TLS Client Code

      Let’s begin writing our TLS client. You will find starter code below. Read it carefully, then refer to the API documentation as needed (docs.python.org/3/library/ssl.html) to complete the code.

      • How do you create a socket and initiate a connection?
      • What is an SSL Context, and what parameters does the context require?
      • How do we use the context with the connection?
      import ssl
      import socket
      import time
      
      hostname = # TODO - Set hostname to localhost
      port =     # TODO - Set the port number you are listening on in OpenSSL
      
      # This function handles communication once the TLS connection is established.
      # TODO: Read and understand what it does. Nothing to change here.
      # Understand what the server needs to do to close the connection.
      def handle(conn):
          KEEP_ALIVE = True
          while KEEP_ALIVE:
              print("PING...")
              conn.write(b'PING...')
              time.sleep(1)
              res = conn.recv().decode().strip()
              if res == "HELLO" and KEEP_ALIVE:
                  print("Received HELLO, sending CLIENT ALIVE...")
                  conn.write(b'CLIENT ALIVE...')
              elif res != "HELLO" and KEEP_ALIVE:
                  KEEP_ALIVE = False
                  print("No HELLO received, closing the connection")
                  conn.write(b'CLIENT CLOSING...')
                  conn.close()
      
      # TODO - Refer to https://docs.python.org/3/library/ssl.html
      # TODO - Complete the code below
      def main():
          sock = # TODO add the connection parameters
          context = # TODO create SSL context
          context.load_verify_locations() # TODO specify the path to the certificate
          context.verify_flags # TODO - Disable strict X.509 checks (self-signed)
          conn = # Wrap the socket with SSL
          try:
              handle(conn)
          except Exception as e:
              print(e)
          finally:
              conn.close()
      
      main()

      Run the code. In the server side you can type replies to the client in the command line.

      • tls
      • sockets
      Show worked solution
      import ssl
      import socket
      import time
      
      hostname = 'localhost'
      port = 4444
      
      def handle(conn):
          KEEP_ALIVE = True
          while KEEP_ALIVE:
              print("PING...")
              conn.write(b'PING...')
              time.sleep(1)
              res = conn.recv().decode().strip()
              if res == "HELLO" and KEEP_ALIVE:
                  print("Received HELLO, sending CLIENT ALIVE...")
                  conn.write(b'CLIENT ALIVE...')
              elif res != "HELLO" and KEEP_ALIVE:
                  KEEP_ALIVE = False
                  print("No HELLO received, closing the connection")
                  conn.write(b'CLIENT CLOSING...')
                  conn.close()
      
      def main():
          sock = socket.create_connection((hostname, port))
          context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
          context.load_verify_locations("certificate.crt")
          context.verify_flags &= ~ssl.VERIFY_X509_STRICT
          conn = context.wrap_socket(sock, server_hostname=hostname)
          try:
              handle(conn)
          except Exception as e:
              print(e)
          finally:
              conn.close()
      
      main()

      The trailing # TODO comments on the completed lines are cut off in the released PDF, so they are left out here.

      How do you create a socket and initiate a connection?

      • Define the host (IP address or localhost) and port
      • Create an SSL context
      • Create the connection

      Explain what an SSL context is and what parameter the context needs.

      • It contains parameters related to the TLS connection (see the Python ssl documentation on SSL contexts).
      • SERVER_AUTH: authenticate only the server; i.e., the server sends a certificate and the client verifies it.

      How do we use the context with the connection?

      We wrap the socket with the SSL context using the wrap_socket method.

      The solution uses port 4444, while the server command in Section 2 listens on 4443. Use the port your own s_server is listening on.

      Revise: TLS: design rationale and the socket abstraction.

    • t08-q4

      Tutorial_8_Questions.pdf

      analysedesign

      Section 4: Extension, Improving Security

      Back to the client. Modify it such that:

      • It verifies that the Organization and Organizational Unit in the server certificate have the correct values:
        • O (Organization) = The University of Sydney
        • OU (Organizational Unit) = The School of Computer Science

      Why is it necessary for localhost to appear in the Common Name (CN) field?

      import ssl
      import socket
      import time
      
      hostname = 'localhost' ### TODO - Set hostname to localhost
      port = 4444 ### TODO - Set the port number you are listening in openssl
      
      ### This function handles the communication once the TLS connection is established.
      ### TODO Read and understand what it does. Nothing to change here.
      def handle(conn):
          KEEP_ALIVE=1
          while KEEP_ALIVE==1:
              print("PING...")
              conn.write(b'PING...')
              time.sleep(1)
              res = conn.recv().decode().strip()
              if res == "HELLO" and KEEP_ALIVE==1:
                  print("Received HELLO, sending PING")
                  conn.write(b'CLIENT ALIVE...')
              elif res != "HELLO" and KEEP_ALIVE==1:
                  KEEP_ALIVE=0
                  print("No HELLO received, Closing the connection")
                  conn.write(b'CLIENT CLOSING...')
                  conn.close()
      
      ### TODO - Have a look here https://docs.python.org/3/library/ssl.html
      ### TODO - And complete the codes
      def main():
          sock = # TODO add the connection parameters
          context = # TODO create SSL context
          context.load_verify_locations() # TODO specify the path to the certificate
          context.verify_flags # TODO - Disable strict X.509 checks (self-signed)
          conn = # Wrap the socket with SSL
          cert = ### TODO - Use the getpeercert() method to access the certificate
          subject = dict(x[0] for x in cert['subject'])
          organizationName = ### TODO - Extract organizationName from subject
          organizationalUnitName = ### TODO - Extract organizationalUnitName from subject
          print(organizationName)
          print(organizationalUnitName)
          if ### TODO Add the if condition to check O and OU
              try:
                  handle(conn)
              except Exception as e:
                  print(e)
              finally:
                  conn.close()
      
      main()
      • tls
      • certificates
      • x509
      Show worked solution
      def main():
          sock = socket.create_connection(("localhost", port))
          context = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
          context.load_verify_locations("certificate.crt")
          context.verify_flags &= ~ssl.VERIFY_X509_STRICT
          conn = context.wrap_socket(sock, server_hostname = hostname)
          cert = conn.getpeercert()
          subject = dict(x[0] for x in cert['subject'])
          organizationName = subject['organizationName']
          organizationalUnitName = subject['organizationalUnitName']
          print(organizationName)
          print(organizationalUnitName)
          if (organizationName=='The University of Sydney' and organizationalUn...
              try:
                  handle(conn)
              except Exception as e:
                  print(e)
              finally:
                  conn.close()
      
      main()

      handle and the imports are unchanged from Section 3. Output of the run:

      The University of Sydney
      The School of Computer Science
      PING...

      The run then ends in a KeyboardInterrupt, raised from conn.recv() inside handle, because the notebook cell was stopped by hand while it waited for a reply.

      Two gaps in the released solution:

      • The if line is cut off in the PDF after organizationalUn. The condition compares organizationName with 'The University of Sydney' and the OU with 'The School of Computer Science'; the rest of the line is not in the source.
      • The solution gives no answer to the question about why localhost must appear in the CN field.

      Revise: Public-key certificates and X.509.

    • t08-q5

      Tutorial_8_Questions.pdf

      applycommand

      Section 5: Capturing Packets

      Next, we are going to use the packet capture tool tshark to capture the packets exchanged between your client and the TLS server running in the VM.

      • Go to the /tmp directory and run the command:

        sudo tshark -i lo -w ./capture.pcap

        Here, lo refers to the loopback interface on which our server is listening.

      • While tshark is running, execute your client code again, then press Ctrl+C to stop capturing.

      • If everything is working correctly, you will see an output like: Capturing on 'Loopback: lo'

      • Download the capture file to your local machine.

      • Download and install Wireshark on your computer from www.wireshark.org.

      • Open the capture.pcap file using Wireshark.

      • Find the communication between your client and the OpenSSL server. Hint: A TLS communication starts with a Client Hello message. Do a regular expression search.

      • Once you find the packet, right-click and use the Follow TCP Stream option to get the full message flow.

      • Inspect the payload tab for the packet content.

      Question

      • What TLS version does the communication use?
      • What is the selected Cipher Suite?

      Certificate homework: try the above with your own self-signed certificate

      Use the link below to learn how to create your own self-signed certificate in Ubuntu: learn.microsoft.com/en-us/azure/application-gateway/self-signed-certificates

      Verify that when you specify a different hostname in the certificate, the code above no longer works.

      • tls
      • handshake
      • tls-1-3
      Show worked solution

      In Wireshark the message flow appears as a PCAP trace. The released solution shows it as a screenshot, which does not survive text extraction, so only the answers are reproduced here.

      • TLS version: TLS 1.3
      • Selected cipher suite: TLS_AES_256_GCM_SHA384

      The released solution gives no worked answer for the closing exercise (your own self-signed certificate with a different hostname). It repeats the instruction only.

      Revise: The TLS handshake, 1.2 and 1.3.

    • t09-q1

      Tutorial_9_Questions.pdf

      applycommand

      Tutorial 9: Network Security - Firewalls

      In this tutorial, we use the open-source, container-based network emulator Kathara to build a network of two LANs and one WAN connection. Our firewall is a Linux router running iptables as the firewall software. iptables doesn’t have the full functionalities of a commercial firewall or an open source firewall, such as pfSense. However, it is sufficient to learn basic concepts of rule ordering and shadowing.

      Prerequisites

      Everything you need is pre-installed in the VM. Get the lab folder (/home/ubuntu/Tutorial_9/kathara-lab/) onto your machine. All commands from this tutorial must be run inside that folder. It is better to do this tutorial through an SSH session and in the Jupyter Notebook.

      Check whether Kathara is running OK.

      kathara check

      Know the lab topology

      The lab topology consists of two private networks and one public network within a firewall sitting between them. In contrast to the given figure, note that there is no explicit switch device in our simulated network. That is because in Kathara, a collision domain (here lan1, lan2, wan) is itself a shared Ethernet segment, which in fact is the switch.

      Start the whole scenario:

      kathara lstart --noterminals

      This starts every device. You can use kathara list to list all the devices in the network. You can use kathara exec / kathara connect to execute commands or connect to various devices in the network.

      kathara connect pc1        # interactive shell on a pc1

      Question (a)

      Use ifconfig and find out the ip addresses of all the devices. You can do either in the individual terminals of the devices or using kathara connect <device name>, followed by ifconfig. In the firewall use the ip -brief address command.

      If something goes wrong and you want to restart, use kathara lclean and restart issuing the above commands.

      The figure of the topology is an image in the PDF and did not extract. Open Tutorial_9_Questions.pdf to see it.

      • firewall
      • iptables
      • kathara

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: What a network firewall does, and what it cannot stop.

    • t09-q2

      Tutorial_9_Questions.pdf

      recallconceptual

      Question (b)

      Why do the collision domains (lan1, lan2) / the “LAN switches” have no IP address?

      • firewall
      • kathara
      • network-security

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: What a network firewall does, and what it cannot stop.

    • t09-q3

      Tutorial_9_Questions.pdf

      recallconceptual

      Question (c)

      What is the firewall’s additional function, and what turns it on?

      • firewall
      • iptables
      • kathara

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: What a network firewall does, and what it cannot stop.

    • t09-q4

      Tutorial_9_Questions.pdf

      applyconceptual

      Read the firewall rules

      kathara exec firewall -- iptables -L FORWARD -v -n --line-numbers

      Things to understand while reading it:

      • The FORWARD chain holds the rules for traffic passing through the firewall between subnets. Rules are evaluated top to bottom; the first match wins.
      • A rule with -i eth0 matches traffic entering from LAN1; -i eth1 matches traffic entering from LAN2. This is the equivalent of the pfSense “LAN1 interface” and “LAN2 interface” rule tabs.
      • The first rule (ctstate RELATED,ESTABLISHED) makes the firewall stateful: replies to a connection the firewall already allowed out are let back automatically, exactly like pfSense.

      Focus on what happens to Ping (ICMP) traffic, then predict the outcome of each of these before you test them:

      • Ping pc2 from pc1
      • Ping pc1 from pc2
      • Ping webserver1 from pc1
      • Ping pc2 from webserver1
      • Ping webserver1 from pc2

      The rule listing is printed by the command in your own lab, so it is not reproduced here.

      • firewall
      • iptables
      • stateful
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Stateful matching and Spoofing and shadowing.

    • t09-q5

      Tutorial_9_Questions.pdf

      analysecommand

      Verify your predictions

      Open a shell on each device (kathara connect pc1) and ping, or run one-liners:

      kathara exec pc1        -- ping -c3 192.168.2.2  # pc1 -> pc2
      kathara exec pc2        -- ping -c3 192.168.1.3  # pc2 -> pc1
      kathara exec pc1        -- ping -c3 192.168.1.4  # pc1 -> webserver1
      kathara exec webserver1 -- ping -c3 192.168.2.2  # webserver1 -> pc2
      kathara exec pc2        -- ping -c3 192.168.1.4  # pc2 -> webserver1

      Did they behave as you expected? Look again at the LAN2 rules and explain why the outcomes are asymmetric. Which LAN2 rule never gets used, and why?

      • firewall
      • iptables
      • shadowing
      • stateful

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Spoofing and shadowing.

    • t09-q6

      Tutorial_9_Questions.pdf

      analysedesign

      Fix the rule shadowing

      The system administrator’s real objective was:

      Allow ping (ICMP) between the two subnets (devices in LAN1 can ping devices in LAN2 and vice-versa) and nothing else.

      Edit the firewall rules to achieve this. You can experiment live on the firewall:

      kathara connect firewall
      
      # then use: iptables -L FORWARD --line-numbers
      #           iptables -D FORWARD <num>           (delete a rule)
      #           iptables -I FORWARD <num> ...       (insert at a position)

      When you have finished, clean up:

      kathara lclean

      The sheet ends here. It lists no further exercises.

      • firewall
      • iptables
      • shadowing
      • rule-order

      No solution released. The unit has not published a worked solution for this question. Nothing here substitutes for one — use the tags above to find the topic to revise instead.

      Revise: Spoofing and shadowing and Rule tables and default policy.