程序代做CS代考 SQL scheme python x86 javascript dns database crawler chain compiler Java DHCP cache algorithm Nicholas & Peyrin CS 161 Summer 2021 Computer Security

Nicholas & Peyrin CS 161 Summer 2021 Computer Security
For questions with circular bubbles, you may select exactly one choice on Examtool. Unselected option
Final
Only one selected option
For questions with square checkboxes, you may select one or more choices on Examtool.
You can select
multiple squares
For questions with a large box, you need to write your answer in the text box on Examtool.
There is an appendix at the end of this exam, containing descriptions of all C functions used on this exam.
You have 170 minutes, plus a 10-minute buffer for distractions or technical difficulties, for a total of 180 minutes. There are 12 questions of varying credit (200 points total).
The exam is open note. You can use an unlimited number of handwritten cheat sheets, but you must work alone.
Clarifications will be posted on Examtool.
Q1 MANDATORY – Honor Code (5 points) Read the following honor code and type your name on Examtool.
I understand that I may not collaborate with anyone else on this exam, or cheat in any way. I am aware of the Berkeley Campus Code of Student Conduct and acknowledge that academic misconduct will be reported to the Center for Student Conduct and may further result in, at minimum, negative points on the exam and a corresponding notch on Nick’s demolition tool.
Solution: Everyone gets 5 free points for making it to the end of the semester!
Page 1 of 31

Q2 True/false (30 points) Each true/false is worth 2 points.
Q2.1 True or False: TLS with Diffie-Hellman is still vulnerable to man-in-the-middle attackers by intercepting and performing two separate key exchanges with both sides.
True False
Q2.2 True or False: In TLS, an attacker cannot change the client and server random values Rb and Rs sent at the beginning of the exchange undetected, even though the client and server have not yet agreed on a set of symmetric keys.
True False
Solution: True. MACs over the entire dialogue are sent at the end of the handshake in order to verify that no communication was tampered with. If the attacker tampers with Rb or Rs, the exchanged MACs will not match, and the tampering will be detected.
After the exam, we decided that the wording on this question was ambiguous (particularly the phrase about not yet agreeing on a set of symmetric keys), so this question was dropped, and all students received credit.
Final
Page 2 of 31
CS 161 – Summer 2021
Solution: False. In TLS, the server’s public parameter ga mod p is signed by the server, so an attacker cannot modify this value.
Q2.3 True or False: Referrer validation is a valid defense against reflected XSS attacks.
Clarification during exam: This question has been dropped. All students will receive credit on this question.
True False
Solution: The intended solution was false: Referrer validation is a defense against CSRF attacks.
However, referrer validation could stop some reflected XSS attacks. For example, if the victim clicks on a reflected XSS link on the attacker’s website, the server could see the request came from the attacker’s website and reject the request.
Because the answer was ambiguous, we dropped this question and gave everyone full points.
Q2.4 True or False: Hybrid encryption typically uses symmetric encryption to encrypt the plaintext and asymmetric encryption to encrypt a symmetric key.
True
False

Solution: True.Hybridencryptionusessymmetricencryptiontoencryptthemessagebecause it is fast and can handle arbitrary-length ciphertexts, and asymmetric encryption is only used to encrypt the symmetric key because it is slow and can only handle ciphertexts up to a certain length.
Q2.5 True or False: If the first and last node in a Tor circuit learn that they are part of the same circuit and collude with one another, they are able to deanonymize the Tor user, even if the middle node is honest.
True False
Q2.6 True or False: One advantage of pointer authentication over stack canaries is that pointer authentication is harder to brute-force than stack canaries.
True False
Q2.7 True or False: While developing a website, the programmer leaves the server password hidden in the website’s HTML. This violates Shannon’s Maxim.
True False
Q2.8 TrueorFalse:MostCAPTCHAsaresetuptodistinguishgoodbots,suchaswebcrawlers,from malicious bots.
True False
Q2.9 True or False: Cursorjacking is a UI attack that relies on creating a fake cursor that is more prominent or visible than the real cursor.
Solution: True. The middle node of the Tor circuit exists to defend against the attack where the entry node directly contacts the exit node to collude. If they are able to bypass this, then the anonymity guarantees are lost.
Solution: False. A brute-force attack is easier with pointer authentication because there are fewer unused bits in a pointer authentication code (PAC) (around 25 bits on a 64-bit system) compared to the randomized bytes of the stack canary (56 bits on a 64-bit system).
Final
Page 3 of 31 CS 161 – Summer 2021
Solution: True. The programmer is relying through security through obscurity, which is a violation of Shannon’s Maxim.
Solution: False. CAPTCHAs can only distinguish between bots and humans.

True False
Q2.10 TrueorFalse:Inaprogramthathasstackcanariesenabled,thestackcanarytakesonthesame value across multiple executions of the program.
True False
Q2.11 True or False: If Alice encrypts a message with AES-CBC, but instead of using completely random IVs, she uses R, R + 1, R + 2, and so on, where R is a random value that she chose once, this scheme is IND-CPA secure.
True False
Q2.12 True or False: DNSSEC uses TLS to protect against attacks when transmitting packets. True False
Q2.13 True or False: SHA-256 is a good hash function to use when hashing passwords. True False
Q2.14 TrueorFalse:Afirewalldoesnotdefendagainstatrustedpartyinsidethefirewallthatbecomes malicious and attempts to breach other computers within the network.
True False
Q2.15 True or False: One weakness of one-time authentication codes, such as those sent to a user’s cell phone number, is that they are still vulnerable to a transient phishing attack.
Solution: True. This is the definition of cursorjacking.
Solution: False. The stack canary takes on a different value every time the program is run.
Solution: False.Asseenindiscussion,iftheattackercanpredictfutureIVsinAES-CBC,then AES-CBC is not IND-CPA secure.
Solution: False.DNSSECusesUDPandofflinesignaturesprotectrecords.(RecallthatDNSSEC is supposed to be fast and lightweight, and TLS is slower because of a long handshake.)
Solution: False.SHA256isafasthashfunction,whichwouldallowofflinepasswordguessing attacks to be done efficiently. Instead, a slow hash function such as PBKDF2 or Argon2 would be better since it makes brute-force attacks mostly infeasible.
Final
Page 4 of 31 CS 161 – Summer 2021
Solution: True.Firewallsassumethatusersinsidethefirewallaretrusted,soamalicioususer inside the network has unlimited power to attack other machines inside the network.

True False
Q2.16 (0 points) True or False: EvanBot is a real bot.
Solution: True. Transient phishing attacks simply trick the user into entering the one-time code sent by the legitimate service, and then the attackers use the code to access the account themselves.
Final
Page 5 of 31
CS 161 – Summer 2021
True
False
Solution: True. EvanBot always fails CAPTCHAs.

Q3 (18 points) Q3.1 (5 points) Which of the following URLs have the same origin as http://piazza.com/? Select
all that apply.
(A) https://piazza.com/
(B) http://piazza.com:614/ (C) http://web.piazza.com/ (D) http://piazza.com/run (E) http://aplaza.com/
(F) None of the above
Solution: Recall that the same-origin policy requires that the protocol, domain, and port number must match. The port number is assumed to be 80 for HTTP and 443 for HTTPS.
A: False. The protocols (and default port numbers) don’t match.
B: False. The port numbers don’t match.
C: False. The domain names don’t match.
D: True. The protocols, port numbers, and domain names all match. E: False. The domain names don’t match.
Final
Page 6 of 31 CS 161 – Summer 2021
Q3.2 (3 points) If the script is in- cluded in http://piazza.com/, which of these pages can the script modify?
(G) http://piazza.com/ (J) All of the above
(H) http://bank.com/ (I) http://cs161.org/
(K) None of the above
(L)
Solution: JavaScripthastheoriginofthepagethatloadsit,sothescriptcanonlymodifypages on the http://piazza.com origin. Only the selected answer choice matches the protocol, domain name, and port number.
Q3.3 (5 points) In which of the following contexts would the contents of a cookie with the HttpOnly flag be sent? Select all that apply.
(A) A user clicks on a link that sends a request over HTTP to the domain of the cookie (B) A user clicks on a link that sends a request over HTTPS to the domain of the cookie

(C) JavaScript is used to send a request over HTTP to the domain of the cookie
(D) JavaScript is used to read the value of the cookie and send its contents to a different domain (E) A page includes an tag loading an image using HTTP from the domain of the cookie (F) None of the above
Q3.4 (5 points) http://evanbot.piazza.com is setting a cookie. Which of these cookie attributes can http://evanbot.piazza.com set (without being rejected by the browser) so that the cookie gets sent on a request to http://web.piazza.com/pictures? Select all that apply.
(G) domain=evanbot.piazza.com; path=/pictures (H) domain=piazza.com; path=/pictures
(I) domain=com; path=/pictures
(J) domain=evanbot.piazza.com
(K) domain=piazza.evanbot.com; path=/pictures (L) None of the above
Solution: HttpOnly only prevents JavaScript from directly reading the value of a cookie, but it does not prevent it being sent as a cookie in in any requests to the domain, even if the requests are made in JavaScript. Thus, only option (D) is incorrect because JavaScript attempts to directly read the value of the cookie.
Solution: Recall that cookie policies requires that the domain of the cookie is a domain suffix of the request and that the path of the cookie is a path prefix of the request.
G: False. evanbot.piazza.com is not a domain suffix of web.piazza.com.
H: True. piazza.com is a domain suffix of web.piazza.com, and /pictures is a path prefix
of itself.
I: False. Top-level domains such as com are not a valid cookie domain.
J: False. evanbot.piazza.com is not a domain suffix of web.piazza.com. K: False. piazza.evanbot.com is not a domain suffix of web.piazza.com.
Final
Page 7 of 31
CS 161 – Summer 2021

Q4 Coffee-Shop Attacks (17 points) Dr. Yang comes to MoonBucks and tries to connect to the network in the coffee shop. Dr. Yang and http://www.piazza.com are communicating through TCP. Mallory is an on-path attacker.
Q4.1 (5 points) Which of the following protocols are used when Dr. Yang first connects to the Wi- Fi network and visits http://www.piazza.com? Assume any caches are empty. Select all that apply.
(A) CSRF (C) DNS (or DNSSEC) (E) DHCP
(B) IP (D) HTTP (F) None of the above
Solution:
A: False. CSRF is not a protocol, but a web attack.
B: True. IP is used to send messages across the internet and is used by TCP, which is used by TLS, which is used by HTTPS.
C: True. DNS is used to look up the IP address of www.piazza.com.
D: True. HTTP is the application protocol being used.
E: True. DHCP is used to receive the initial network configuration for the client.
Q4.2 (3 points) Suppose Mallory spoofs a packet with a valid, upcoming sequence number to inject the malicious message into the connection. Would this affect other messages in the connection?
(G) Yes, because the malicious message replaces some legitimate message
(H) Yes, because future messages will arrive out of order
(I) No, because on-path attackers cannot inject packets into a TCP connection (J) No, because TCP connections are encrypted
(K)
(L)
Q4.3 (3 points) To establish a TCP connection, Dr. Yang first sends a SYN packet with Seq = 980 to the server and receives a SYN-ACK packet with Seq = 603; Ack = 981. What packet should Dr. Yang include in the next packet to complete the TCP handshake?
(A) SYN-ACK packet with Seq = 981; Ack = 604
Solution: When the server receives the original TCP packet whose sequence number was used by Mallory, the server will ignore it, thinking that it has already received its data and that it was retransmitted.
Final Page 8 of 31 CS 161 – Summer 2021

(B) SYN-ACK packet with Seq = 604; Ack = 981
(C) ACK packet with Seq = 981; Ack = 604
(D) ACK packet with Seq = 604; Ack = 981
(E) Nothing to send, because the TCP handshake is already finished. (F)
Q4.4 (3 points) Immediately after the TCP handshake, Mallory injects a valid RST packet to the server. Next, Mallory spoofs a SYN packet from Dr. Yang to the server with headers Seq = X. The server responds with a SYN-ACK packet with Seq = Y ; Ack = X + 1. What is the destination of this packet?
Final
Page 9 of 31
CS 161 – Summer 2021
Solution: Thisisthethirdstepofthe3-wayhandshake,whentheclientsendsanACKpacket to acknowledge the server’s SYN-ACK packet.
(G) Dr. Yang (H) The server (I) Mallory
(J) None of the above
(K) (L)
Solution: The server uses the source as the destination for the SYN-ACK packet. Because Mallory spoofed the packet from the client, the response is sent to the client.
Q4.5 (3 points) Which of the following network attackers would be able to perform the same attacks as Mallory?
Clarification during exam: By “perform the same attacks,” we mean “reliably perform the same attacks.”
(A) A MITM attacker between Dr. Yang and the server
(D) None of the above
(E) (F)
(B) An off-path attacker (C) All of the above
Solution: A MITM attacker has all the capabilities of an on-path attacker, so it would be able to perform Mallory’s attacks. An off-path attacker would be unable to guess the sequence numbers and would be unable to perform Mallory’s attacks.

Q5 Dual Asymmetry (15 points) Alice wants to send two messages M1 and M2 to Bob, but they do not share a symmetric key.
Clarification during exam: Assume that p is a large prime and that g is a generator modp, like in ElGamal. Assume that all computations are done modulo p in Scheme A.
Q5.1 (3 points) Scheme A: Bob publishes his public key B = gb. Alice randomly selects r from 0 to p-2. Alice then sends the ciphertext (R, S1, S2) = (gr, M1 × Br, M2 × Br+1).
Select the correct decryption scheme for M1:
(A)R−b×S1 (D)Bb×S1
(E) (C)B−b×S1 (F)
(B) Rb × S1
Solution:
S1 = M1 × Br
S1 = M1 × gbr M1 = g−br × S1 M1 =R−b ×S1
Given in the question Substitute B = gb
Multiply both sides by g−br SubstituteR=gr
Q5.2 (3 points) Select the correct decryption scheme for M2:
(G)B−1 ×R−b ×S2 (H)B×R−b ×S2 (I)B−1 ×Rb ×S2
(J)B−1 ×R×S2 (K)
(L)
Solution:
S2 = M2 × Br+1 S2 = M2 × gb(r+1) S2 = M2 × gbr+b
M2 = g−br−b × S2
M2 = g−br × g−b × S2 M2 = R−b × B−1 × S2 M2 = B−1 × R−b × S2
Given in the question Substitute B = gb Exponentiation properties Multiply both sides by g−br−b Exponentiation properties Substitute B = gb and R = gr Rearrange terms
Final
Page 10 of 31
CS 161 – Summer 2021

Q5.3
(4 points) Is Scheme A IND-CPA secure? If it is secure, briefly explain why (1 sentence). If it is not secure, briefly describe how you can learn something about the messages.
Clarification during exam: For Scheme A, in the IND-CPA game, assume that a single plaintext is composed of two parts, M1 and M2.
(A) Secure (C) (E)
Q5.4
(5 points) Scheme B: Alice randomly chooses two 128-bit keys K1 and K2. Alice encrypts K1 and K2 with Bob’s public key using RSA (with OAEP padding) then encrypts both messages with AES-CTR using K1 and K2. The ciphertext is RSA(PKBob, K1∥K2), Enc(K1, M1), Enc(K2, M2).
Which of the following is required for Scheme B to be IND-CPA secure? Select all that apply. (G) K1 and K2 must be different
(H) A different IV is used each time in AES-CTR
(I) M1 and M2 must be different messages
(J) M1 and M2 must be a multiple of the AES block size (K) M1 and M2 must be less than 128 bits long
(L) None of the above
(B) Not secure (D)
(F)
Solution: This scheme is not IND-CPA secure. Eve can determine if M1 = M2 by checking if S2 = S1 × B.
Solution:
G: False. Because Enc is an IND-CPA secure encryption algorithm, the key does not need to be changed between two encryptions.
H: True. AES-CTR requires that a unique nonce is used for each encryption, or it loses its confidentiality guarantees.
I: False. A secure encryption algorithm would not leak the fact that two messages are the same. J: AES-CTR can encrypt any length of plaintext. Padding is not needed in AES-CTR.
K: AES-CTR can encrypt any length of plaintext.
Final
Page 11 of 31
CS 161 – Summer 2021

Q6 Under Pressure (16 points) Alice and Bob are communicating large pieces of secret data with each other using an IND-CPA secure encryption scheme, but they are being slowed down by their connection! They decide to use compression to improve the amount of data they can send.
Consider the following properties of compression algorithms:
• Compression algorithms reduce the length of the input.
• High-entropy (random-looking) data may only have its length reduced slightly, or not at all • Low-entropy (predictable) data can often have its length reduced considerably
Q6.1 (3 points) Alice and Bob consider first encrypting and then compressing their data. They send compress(Enc(K, M )), where the input to the compression algorithm is the output of the encryp- tion algorithm. Provide one reason why this might be a bad idea.
Q6.2 (5 points) Realizing their mistake, Alice and Bob instead decide to compress their data before encrypting it. They send Enc(K, compress(M )), where the input to the encryption algorithm is the output of the compression algorithm.
True or False: This combination of compress-then-encrypt is IND-CPA secure. If you answer True, briefly justify your answer (no formal proof needed). If you answer False, describe how an adversary could win the IND-CPA game with probability greater than 0.5.
(G) True (H) False (I) (J) (K) (L)
Solution: Encryption produces high-entropy, random-looking outputs. This means that at- tempting to compress the ciphertext will likely yield little to no compression.
Solution: Notice that the length of the ciphertext is now dependent on properties of the plaintext (other than the length of the plaintext). Our typical assumption is that the length of the ciphertext only leaks the length of the plaintext, but this is not true with compress-then- encrypt constructions.
The adversary can send M0 = 0128 (128-bit message consisting solely of 0’s) and M1 as a pseudorandom, 128-bit message. If the oracle encrypts M0, the result of compress(M0) will be short, and the resulting ciphertext will be short. If the oracle encrypts M1, the result of compress(M1) will be about as long as the original message, and the resulting ciphertext will be long. The adversary can thus win the IND-CPA game with probability of 1.
For the rest of this question, consider a compress-then-encrypt algorithm with the following properties:
• Assume that Alice and Bob’s messages consist of byte strings.
• When compressing, any chain of m consecutive, identical runs of n bytes (total length mn) are compressed into a single run of length n. Runs consisting of a single byte (n = 1) are included.
• Encryption preserves the exact length of the message (no padding is used). For example, the following sequence of bytes:
Final Page 12 of 31 CS 161 – Summer 2021

Index 0 1 2 3 4 5 6 7 8 9 Byte 0x00 0x11 0x22 0x33 0x44 0x44 0x55 0x66 0x77 0x77
would be compressed to a message of length 8, since there are 2 1-byte runs in positions 4–5 and 8–9. Similarly, the following sequence of bytes:
Index 0 1 2 3 4 5 6 7 8 9 Byte 0xaa 0xbb 0xaa 0xbb 0xcc 0xdd 0xcc 0xdd 0xee 0xff
would be compressed to 6 bytes, since there are two 2-byte runs in positions 0–3 and two 2-byte runs in positions 4–7.
Q6.3
(5 points) Alice sends the same message M = secret repeatedly to Bob, using the compression algorithm from above for a compress-then-encrypt scheme.
Assume that Mallory doesn’t have complete control over the messages that Alice sends, but Mallory is able to append to the sent messages before they are compressed and encrypted.
For example, if Alice repeatedly sends the message M = secret, Mallory can force the compressed and encrypted message to be M′ = secret∥x, where x is chosen by Mallory. She can do this repeatedly for any value of x that she chooses.
If Mallory can observe all resulting ciphertexts from the compress-then-encrypt algorithm as they are transmitted to Bob, devise a way to recover the last byte of secret.
Clarification during exam: Assume that Alice’s messages will never produce ambiguous behavior when being compressed.
Clarification during exam: Assume that the encryption algorithm preserves the exact length of the plaintext.
Solution: The solution here is to rely on the information leakage through the length of the ciphertext. Observe that, if the last byte of message matches the first byte of Mallory’s appended portion of the message x, the message would be shorter than if they were different.
Using this, Mallory only needs to try 256 different messages to learn the last byte of the message. When the ciphertext length is 1 less than for all other possible bytes, we know the chosen byte is the last byte of secret.
Q6.4
(3 points) Assume that Mallory has a method for recovering the last byte of the message. If secret is 32 bytes long and there are 256 possible values for a byte, what is the most number of messages Alice has to send (that Mallory can append to) in order to learn the entire secret?
(G) 2128 (H) 2256
(I) 32256
(J) 256 × 32
(K) 25632
(L) None of the above
Solution: Once Mallory learned the last byte of secret, she can fix that byte of her message and move on to the next byte. Because the compression algorithm is able to detect arbitrary lengths of runs, if we know that the last byte of the message is x, Mallory can append y∥x
Final
Page 13 of 31
CS 161 – Summer 2021

to the message, trying every byte y. When y is equal to the second-to-last byte of secret, the message length will be 2 less than it would be otherwise. This process can be repeated for all 32 bytes of the message, totalling 256 × 32 messages at most.
Final Page 14 of 31 CS 161 – Summer 2021

Q7
TLS Secret Chaining (12 points) Recall that TLS with RSA does not provide forward secrecy. An attacker who has recorded past connections and then stolen the server’s private key can decrypt any past connection.
Consider a modified TLS scheme. RSA is used for the first connection. In future connections, the premaster secret is instead encrypted using the cipher key from the previous connection. Assume this encryption is IND-CPA secure.
The server and client perform n TLS connections. The first connection is numbered C1, and the most recent connection is numbered Cn. The attacker records some of these connections and then steals the server’s private key. For each set of recorded connections, select all connections the attacker can decrypt.
Clarification during exam: Assume that ranges of connections are inclusive. For example, “All connections between C1 and Cn” would include C1 and Cn.
Q7.1 (3 points) The attacker records all connections except C1.
(A) Connection C1 only
(B) Connections C1 and C2 only (C) All connections except C1
(D) All connections between C1 and Cn−1 (E) All connections between C1 and Cn (F) None of the above
Q7.2 (3 points) The attacker records all connections except Cn.
(G) Connection C1 only
(H) Connections C1 and C2 only (I) All connections except C1
(J) All connections between C1 and Cn−1 (K) All connections between C1 and Cn (L) None of the above
Q7.3 (3 points) The attacker records all connections except C2.
(A) Connection C1 only
(B) Connections C1 and C2 only (C) All connections except C1
(D) All connections between C1 and Cn−1 (E) All connections between C1 and Cn (F) None of the above
Solution: Notice that, in order to learn the premaster secret for Ci, you need to know the PS for Ci−1, since Ci’s PS was encrypted with information derived from the PS of Ci−1. For C1, the PS is encrypted with the server’s public key, so all connections between C1 and Ci need to be recorded in order to decrypt connection Ci. Missing just one connection removes the ability to learn the PS for every subsequent connection.
Final
Page 15 of 31
CS 161 – Summer 2021

Q7.4 (3points) SupposewemodifytheTLSschemefromabove.Ineveryconnection,theclientencrypts their random number Rb with RSA before sending it to the server. (Recall that in regular TLS, Rb is sent with no encryption.)
Does this scheme provide forward secrecy?
(G) Yes, because Rb is needed to generate the symmetric keys
(H) Yes, because an attacker can perform a replay attack
(I) No, because the attacker can still learn Rb after stealing the private key (J) No, because only Diffie- LS provides forward secrecy
(K)
(L)
Solution: No. If an attacker records the connection and later steals the private key of the connection, they can decrypt the encrypted Rb (as well as the premaster secret) in order to learn the master secret and break secrecy.
Final
Page 16 of 31
CS 161 – Summer 2021

Q8 Intrusion Detection Scenarios (12 points) For each scenario below, select the best detector or detection method for the attack.
Q8.1 (3points) TheattackerconstructsapathtraversalattackwithURLescaping:%2e%2e%2f%2e%2e%2f.
(A) NIDS, because of interpretation issues (D) HIDS, because of cost
(B) NIDS, because of cost
(C) HIDS, because of interpretation issues
(E) (F)
Solution: This path traversal attack is masked using percent encoding in URLs. A traditional NIDS might not recognize this since it is specific to HTTP servers, so a HIDS would be the best option here in order ot avoid the interpretation issues of percent encoding.
Q8.2 (3 points) The attacker is attacking a large network with hundreds of computers, and a detector must be installed as quickly as possible.
(G) NIDS, because of interpretation issues (H) NIDS, because of cost
(I) HIDS, because of interpretation issues
(J) HIDS, because of cost
(K) (L)
Solution: A major advantage of NIDS is that they can be quickly installed in order to cover an entire network. Because of the time constraints, the NIDS would be the best in order to mitigate the time cost.
Q8.3 (3 points) The attacker constructs an attack that is encrypted with HTTPS. (A) NIDS, because of interpretation issues (D) HIDS, because of cost
(B) NIDS, because of cost
(C) HIDS, because of interpretation issues
(E) (F)
Solution: A NIDS is not able to decrypt data since it doesn’t have the keys that are stored on the host. Thus, only the host can decrypt an interpret the requests, and a HIDS would be the best IDS to use here.
Final
Page 17 of 31 CS 161 – Summer 2021
Q8.4 (3 points) The attacker constructs a buffer overflow attack using shellcode they found online in a database of common attacks.

Final
Page 18 of 31
CS 161 – Summer 2021
(G) Signature-based (H) Specification-based (I) Anomaly-based
(J) Behavioral
(K) (L)
Solution: This shellcode is easily obtainable and has not been modified, so a signature that matches the exact shellcode would be most effective in detecting this attack.

Q9 To The Moon (15 points) ToTheMoon Bank has just created an online banking system. When a user wants to complete a transfer, they follow these steps:
1. The user logs in by making a POST request with their username and password.
2. The server sets a cookie with name=auth_user and value=$token, where $token is a session token specific to the user’s login session.
3. The user initiates a transfer by making a GET request to https://tothemoonbank.com/transfer?amount=$amount&to=$user, replacing $amount and $user with the intended amount and recipient. Transfers use a parameterized SQL query.
4. The server runs the SQL query SELECT username FROM users WHERE session_token = ‘$token’, replacing token with the value of the cookie. The server does not use parameter-
ized SQL or any input sanitization.
Q9.1 (4 points) Which of the following attacks are possible in this system? Select all that apply.
(A) SQL injection (D) Path traversal attack (B) ROP attack (E) None of the above
(C) CSRF attack
(F)
Solution: Of the answer options available, the only attacks that are indicated to exist are CSRF in step 3 (because the request does not include a CSRF token). and SQL injection in step 4 (because the server does not use paramaterized SQL or input sanitization).
ROP is a memory safety attack, and path traversal attacks involve filesystems. These are not mentioned in the system, so they aren’t indicated to exist.
Final
Page 19 of 31 CS 161 – Summer 2021
Q9.2 (4 points) Mallory is a malicious user with an account on ToTheMoon Bank. Mallory creates a malicious link https://tothemoonbank.com/transfer?amount=100&to=Mallory.
Which of the following scenarios would cause Alice to send $100 to Mallory? Select all that apply. (G) Alice clicks on the malicious link when Alice is not logged into the bank
(H) Alice clicks on the malicious link when Alice is logged into the bank
(I) Alice visits Mallory’s website, which has an img tag loading the malicious link, when Alice is not logged into the bank
(J) Alice visits Mallory’s website, which has an img tag loading the malicious link, when Alice is logged into the bank
(K) None of the above
(L)

Solution: A CSRF attack would require the user to be logged in on the bank website. After this, any option that makes a GET request would transfer the money, so both an img tag and a link would cause this behavior.
Final
Page 20 of 31
CS 161 – Summer 2021
Q9.3 (4 points) Suppose Step 4 is modified. To initiate a transfer, instead of making a GET request, the user makes a POST request to https://tothemoonbank.com/transfer with the amount and recipient in the POST body.
Which of the following scenarios would cause Alice to send $100 to Mallory? Select all that apply. Clarification during exam: The malicious link in the answer choices should be
https://tothemoonbank.com/transfer?amount=100&to=Mallory.
(A) Alice clicks on the malicious link when Alice is not logged into the bank
(B) Alice clicks on the malicious link when Alice is logged into the bank
(C) Alice visits Mallory’s website, which has an img tag loading the malicious link, when Alice is not logged into the bank
(D) Alice visits Mallory’s website, which has an img tag loading the malicious link, when Alice is logged into the bank
(E) None of the above
(F)
Q9.4 (3 points) Which user inputs might be vulnerable to SQL injection? Select all that apply. (G) amount parameter
(H) to parameter
(I) Value of the auth_user cookie (J) None of the above
(K)
(L)
Solution: Neither the img tag nor the malicious link would cause a POST request to be sent, so none of these options would cause a transfer to take place.
Solution: The question indicates that only the token query in step 4 is vulnerable to SQL injection, so only the value of the auth_user cookie would be vulnerable.

Q10 AES-EMAC
Consider AES-EMAC, which is another scheme for generating secure MACs.
M1 M2 Mn
(19 points)
AES
K1 K1 K1
Sn
S1 S2
K2
Q10.1 (2 points) True or False: Given only T, an attacker can generate a valid MAC for M||M′, for an M′ of the attacker’s choosing.
True False
Q10.2 (2 points) True or False: Given only T and K1, an attacker can generate a valid MAC for M||M′, for an M′ of the attacker’s choosing.
True False
Q10.3 (2 points) True or False: Given only T, K1, and K2, an attacker can generate a valid MAC for M||M′, for an M′ of the attacker’s choosing.
True False
AES
AES
AES
Solution: False. Without the keys, the attacker cannot compute further intermediate states Si.
Solution: False.WithoutK2,theattackercannotoutputavalidfinalstateT,andtheattacker cannot reverse the final AES encryption to learn the intermediate state Sn.
Q10.4 (2 points) True or False: Given the output T and the secret keys K1 and K2, the entire original message M can be reconstructed.
Final
Page 21 of 31 CS 161 – Summer 2021
T
Solution: True. First, the attacker can compute D(T, K2) to retrieve Sn. (In other words, the attacker computes AES decryption on T with key K2).
Then, the attacker adds more intermediate state Sn+1, Sn+2, . . . by performing more AES encryptions using K1.
Finally, the attacker encrypts the last Si block with K2 to produce the final MAC.

True False
For the rest of the question, regardless of your answer to the previous parts, assume that the output is S1||S2 . . . ||Sn||T .
Q10.5 (4 points) Which values are needed to recover the entire original message? Select all that apply. (A)Si forall1≤i≤n (D)K2
(B) T (E) None of the above
Solution: False. One way to see this is to note that the output is only one block long, while the message is n blocks long. There are not enough bits to reconstruct one unique message given the MAC output.
(C) K1
(F)
Solution: Notice that this mode is very similar to CBC mode with a constant 0 IV. In order to recover the message, the output of each encryption block is needed, which corresponds to the states S1 to Sn. In CBC, decryption requires the original key, and K1 corresponds to this key in this mode. Neither K2 nor T are necessary since they would only be used to recover Sn, which is already given to us.
Q10.6 (3 points) Which of these equations is correct for calculating a plaintext block Mi given the output and both keys K1 and K2?
(G) Mi = Dec(K1, Si) ⊕ Si−1 (H) Mi = Dec(K1, Si ⊕ Si−1) (I) Mi = Dec(K2, Si) ⊕ Si−1
(J) Mi = Dec(K2, Si ⊕ Si−1) (K) Mi = Enc(K1, Si) ⊕ Si−1 (L) Mi = Enc(K1, Si ⊕ Si−1)
Solution: By inspecting the diagram, we can write out the equation for encryption: Si = E(K1, Mi ⊕ Si−1). Note that it is very similar to AES-CBC.
Now we can solve for Mi to produce the decryption algorithm:
Si = E(K1, Mi ⊕ Si−1) D(K1, Si) = Mi ⊕ Si−1
D(K1, Si) ⊕ Si−1 = Mi
Encryption equation Decrypt both sides
XOR both sides with Si−1
Q10.7 (4 points) Select all true statements about this scheme.
Final Page 22 of 31 CS 161 – Summer 2021

(A) To compute AES-EMAC on a message, the message must first be padded to a multiple of the block size
(B) Encryption can be parallelized (C) Decryption can be parallelized (D) AES-EMAC is IND-CPA secure (E) None of the above
(F)
Solution:
A: True. The message is split into blocks and each block is encrypted with AES, so the message must be padded to a multiple of the block size.
B: False. Encrypting block i requires the ciphertext from block i − 1, so before we can encrypt block i, we must first wait for block i − 1 to be encrypted.
C: True. The decryption algorithm only depends on ciphertext blocks, not plaintext blocks, and all ciphertext blocks are known at the beginning of decryption.
D: False. There is no randomness involved, so the scheme is deterministic. Deterministic schemes cannot be IND-CPA secure.
Final
Page 23 of 31
CS 161 – Summer 2021

Q11 DNS Lookups (15 points) EvanBot performs a lookup for the IP address of toon.cs161.org. For each DNS or DNSSEC record, determine which name server sent the record.
Q11.1 (3 points) A type record with the IP address of toon.cs161.org
(A) root name server (D) None of the above
(B) .org name server
(C) cs161.org name server
(E) (F)
Solution: This is the final answer record, which is sent by the cs161.org name server.
Q11.2 (3 points) A type record with the IP address of the cs161.org name server (G) root name server (J) None of the above
(H) .org name server
(I) cs161.org name server
(K) (L)
Solution: In this record, the cs161.org name server’s parent name server is redirecting the resolver to the cs161.org name server. The parent of the cs161.org name server is the .org name server.
Q11.3 (3 points) A type record with the IP address of cs161.org (not the name server) (A) root name server (D) None of the above
(B) .org name server
(C) cs161.org name server
(E) (F)
Solution: The IP address of cs161.org was not queried for, and cs161.org is not a name server, so this record will not be sent in this DNS lookup.
Q11.4 (3 points) DNSKEY type record with the public key of the cs161.org name server
Final
Page 24 of 31
CS 161 – Summer 2021
(G) root name server
(H) .org name server
(I) cs161.org name server
(J) None of the above
(K) (L)

Solution: In DNSSEC, each name server sends its own public keys, so this record comes from the cs161.org name server.
Q11.5 (3 points) DS type record with the hash of the .org name server’s public key
(A) root name server
(B) .org name server
(C) cs161.org name server
(D) None of the above
(E) (F)
Solution: In DNSSEC, the DS type record is used by the parent to endorse the child’s public key. In this record, the child is the .org name server, so the parent must be the root name server.
Final
Page 25 of 31
CS 161 – Summer 2021

Q12 Wallet Management
Consider the following vulnerable C code:
1 2 3 4 5 6 7 8 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
Q12.1 (4 points) For the first subpart, assume that no memory safety defenses are enabled.
Let SHELLCODE be a 24-byte malicious shellcode. If the address of wals is 0x9fffcad0, provide an input as a series of Python print statements that would cause your program to execute malicious shellcode.
(26 points)
#include
#include
struct wallet {
char owner[4]; /∗ 4 bytes. ∗/ int amt; /∗ 4 bytes. ∗/
};
int main ( void ) {
int wallet_idx = 0; struct wallet wals [8]; char buf [16];
while (1) {
/∗ Get wallet index . ∗/ printf(“Enter wallet index:\n”); fgets(buf, 16, stdin);
int wallet_idx = atoi(buf);
if ( wallet_idx < 0) { /∗ Exit loop if invalid index. ∗/ break ; } /∗ Update dollar amount . ∗/ printf("Enter dollar amount:\n"); fgets(buf, 16, stdin); wals[wallet_idx].amt = atoi(buf); /∗ Read owner. ∗/ printf("Enter owner name:\n"); gets ( wals [ wallet_idx ] . owner ) ; } return 0; } Final Page 26 of 31 CS 161 – Summer 2021 Assume you are on a little-endian 32-bit x86 system. Assume that there is no compiler padding or additional saved registers in all subparts. Clarification during exam: The atoi function converts a string to an integer. For example, atoi("3") would return the integer value 3. For example, a sequence of non-malicious inputs that updates wallet 0 without exiting the loop would be: print('0') print('1000') print('NN') Write your answer in Python 2 syntax (just like in Project 1). Solution: This is a standard buffer overflow. First, we need to input a '0' to start writing at the beginning of the buffer. Next, we need to input any number to get past the call to update the number of dollars in the wallet. Then, we input our exploit that overflows the buffer in the call to gets. The RIP is located 36 bytes after the start of wals, so we can input the shellcode, followed by 12 dummy bytes, followed by the address of our shellcode. Finally, we need to exit the loop by inputting an invalid index to actually return to the RIP and execute our shellcode: print('0') print('1234') print(SHELLCODE + 'A' * 44 + '\xd0\xca\xff\x9f') print('-1'); For the remaining parts of this question, assume that stack canaries are enabled. Q12.2 (3 points) Complete the stack diagram with stack canaries enabled. Each row represents 4 bytes. Parts (2a), (2b), and (2c): RIP of main (2a) (2b) (2c) (3a) (3b) (3c) (3d) (G) (2a) - SFP of main; (2b) - wallet_idx; (2c) - canary (H) (2a) - SFP of main; (2b) - canary; (2c) - wallet_idx (I) (2a) - canary; (2b) - SFP of main; (2c) - wallet_idx (J) (2a) - canary; (2b) - wallet_idx; (2c) - SFP of main (K) (2a) - wallet_idx; (2b) - SFP of main; (2c) - canary (L) (2a) - wallet_idx; (2b) - canary; (2c) - SFP of main Q12.3 (3 points) Parts (3a), (3b), (3c), and (3d): Final Page 27 of 31 CS 161 – Summer 2021 (A) (3a) - wals[0].amt; (3b) - wals[0].owner; (3c) - wals[1].amt; (3d) - wals[1].owner (B) (3a) - wals[0].owner; (3b) - wals[0].amt; (3c) - wals[1].owner; (3d) - wals[1].amt (C) (3a) - wals[7].amt; (3b) - wals[7].owner; (3c) - wals[6].amt; (3d) - wals[6].owner (D) (3a) - wals[7].owner; (3b) - wals[7].amt; (3c) - wals[6].owner; (3d) - wals[6].amt (E) (F) Solution: The full stack diagram is as follows: RIP of main SFP of main canary wallet_idx wals[7].amt wals[7].owner wals[6].amt wals[6].owner Q12.4 (3 points) Describe, briefly, a vulnerability on line 19. Additionally, describe a one-line fix to line 19 that would make this code memory-safe. Q12.5 (5 points) Let SHELLCODE be a 24-byte malicious shellcode. If the address of the RIP of main is 0xbfeffc80, provide an input as a series of Python print statements that would cause your program to execute malicious shellcode. Solution: Line 19 fails to check for a valid index. While it ensures that the index will never be negative, it should also check that the user does not index past the end of the wals array. Thus, a one-line fix would be to replace the check with if (wallet_idx < 0 || wallet_idx >= 16)
Solution: Now that we have a stack canary in the way, we need be a bit smarter about how we overwrite the RIP. Notice: Because of the indexing vulnerability, we have the ability to write to any address in memory above the start of the wals array by choosing an invalid index.
Each struct wallet is 8 bytes long, so the wallet_idx variable and the canary would appear to be wals[8], and the SFP and RIP of main would appear to be wals[9].
First, we input ‘9’ to maliciously index into the SFP and RIP. Next, we input any number to update the number of dollars. Then, we input our exploit: 4 dummy bytes to overwrite the SFP,
Final
Page 28 of 31 CS 161 – Summer 2021

then input the address of SHELLCODE, which will be 4 bytes after the RIP itself (thus using the address of RIP + 4), then the shellcode. Finally, we input an invalid index to exit the loop:
print(‘9’)
print(‘1234’)
print(‘A’ * 4 + ‘\x84\xfc\xef\xbf’ + SHELLCODE)
print(‘-1’)
Q12.6 (4points) Assumethatthecalltogetsonline31isreplacedwithfread(wals[wallet_idx].owner, 1, 4, stdin). Recall that fread does stop reading at a newline and does not add a NULL termi- nator.
EvanBot thinks that this code is no longer exploitable because the gets function is no longer used. Assume that your 24-byte shellcode must be written in a contiguous block of memory. Is EvanBot correct? If you answer Yes, describe why you can no longer exploit this code. If you answer No, describe how you would write your shellcode to a contiguous block of memory.
(G) Yes (H) No (I) (J) (K) (L)
Solution: In fact, even though fread only directly lets you write every other block of 4 bytes (since it only controls the 4-byte owner field of an 8-byte struct), you can still control a contiguous block of memory through the amt field. By treating 4 bytes of shellcode as a 32-bit integer and outputting its decimal representation, the atoi function will convert the decimal representation back into the raw bits of the shellcode, which will then be written to memory.
Thus, the full algorithm is as follows: For parts of memory written using the owner field, simply output the raw bytes to be read by the fread call. For parts of memory written using the amt field, treat the 4 bytes as a 32-bit integer and output its decimal representation. This allows the attacker to control a contiguous block of memory to place the shellcode.
An alternative solution is to pass the shellcode as an argument or an environment variable to the program, causing it to be placed in memory.
Q12.7
(4 points) This part is independent of the previous subpart, but assume that stack canaries are still enabled. Which of the following actions would individually prevent the attacker from executing malicious shellcode (not necessarily using the exploit from above)?
Clarification during exam: The answer choice “Enabling pointer authentication” has been dropped. All students will receive credit for that answer choice only.
(A) Enabling non-executable pages in addition to stack canaries
(B) Enabling pointer authentication (C)Replacingthecalltogetsonline31withfgets(wals[wallet_idx].owner, 4, stdin) (D) Swapping the positions of the owner and amt fields in the wallet struct
Final
Page 29 of 31 CS 161 – Summer 2021

(E) None of the above
(F)
Solution: A: False. Non-executable pages is trivial to bypass in most circumstances using return-to-libc (which is clearly used in the program) or a ROP attack.
B: Because pointer authentication is only defined in 64-bit systems, and this question uses a 32-bit system, this answer choice is ambiguous, so we gave points to everyone on this answer choice.
C: False. The RIP of main can still be overwritten by indexing into wals[9], and shellcode could be placed elsewhere under the control of the attacker, such as in the environment variables or in the arguments to the program (just like in Project 1 Question 4).
D: False. The call to gets is still vulnerable to a buffer overflow. The attacker just needs to account for the fact that they are now starting to write 4 bytes higher than before.
Final
Page 30 of 31 CS 161 – Summer 2021

C Function Definitions
int printf(const char *format, …);
printf() produces output according to the format string format.
char *gets(char *s);
gets() reads a line from stdin into the buffer pointed to by s until
either a terminating newline or EOF, which it replaces with a null byte
(‘\0’).
char *fgets(char *s, int size, FILE *stream);
fgets() reads in at most one less than size characters from stream and
stores them into the buffer pointed to by s. Reading stops after an
EOF or a newline. If a newline is read, it is stored into the buffer.
A terminating null byte (‘\0’) is stored after the last character in
the buffer.
size_t fread(void *ptr, size_t size, size_t nmemb, FILE *stream);
The function fread() reads nmemb items of data, each size bytes long,
from the stream pointed to by stream, storing them at the location
given by ptr.
Note that fread() does not add a null byte after input.
Final Page 31 of 31 CS 161 – Summer 2021