The previous set of challenges showed how AES performs a keyed permutation on a block of data. In practice, we need to encrypt messages much longer than a single block. A mode of operation describes how to use a cipher like AES on longer messages.
All modes have serious weaknesses when used incorrectly. The challenges in this category take you to a different section of the website where you can interact with APIs and exploit those weaknesses. Get yourself acquainted with the interface and use it to take your next flag!
It is essential that keys in symmetric-key algorithms are random bytes, instead of passwords or other predictable data. The random bytes should be generated using a cryptographically-secure pseudorandom number generator (CSPRNG). If the keys are predictable in any way, then the security level of the cipher is reduced and it may be possible for an attacker who gets access to the ciphertext to decrypt it.
Just because a key looks like it is formed of random bytes, does not mean that it necessarily is. In this case the key has been derived from a simple password using a hashing function, which makes the ciphertext crackable.
For this challenge you may script your HTTP requests to the endpoints, or alternatively attack the ciphertext offline. Good luck!
source.py
from Crypto.Cipher import AES
import hashlib
import random
# /usr/share/dict/words from
# https://gist.githubusercontent.com/wchargin/8927565/raw/d9783627c731268fb2935a731a618aa8e95cf465/words
with open("/usr/share/dict/words") as f:
words = [w.strip() for w in f.readlines()]
keyword = random.choice(words)
KEY = hashlib.md5(keyword.encode()).digest()
FLAG = ?
@chal.route('/passwords_as_keys/decrypt/<ciphertext>/<password_hash>/')
def decrypt(ciphertext, password_hash):
ciphertext = bytes.fromhex(ciphertext)
key = bytes.fromhex(password_hash)
cipher = AES.new(key, AES.MODE_ECB)
try:
decrypted = cipher.decrypt(ciphertext)
except ValueError as e:
return {"error": str(e)}
return {"plaintext": decrypted.hex()}
@chal.route('/passwords_as_keys/encrypt_flag/')
def encrypt_flag():
cipher = AES.new(KEY, AES.MODE_ECB)
encrypted = cipher.encrypt(FLAG.encode())
return {"ciphertext": encrypted.hex()}
# ciphertext = "c92b7734070205bdf6c0087a751466ec13ae15e6f1bcdd3f3a535ec0f4bbae66"
Ở đây, key được lấy từ một file words khá dài và được lấy random. Vì vậy, mình sẽ thử với tất cả key trong đó luôn
from Crypto.Cipher import AES
import hashlib
ciphertext = "c92b7734070205bdf6c0087a751466ec13ae15e6f1bcdd3f3a535ec0f4bbae66"
with open("words") as f:
words = [w.strip() for w in f.readlines()]
for keyword in words:
KEY = hashlib.md5(keyword.encode()).digest()
def decrypt(ciphertext):
ciphertext = bytes.fromhex(ciphertext)
cipher = AES.new(KEY, AES.MODE_ECB)
try:
decrypted = cipher.decrypt(ciphertext)
except ValueError as e:
return {"error": str(e)}
return decrypted.hex()
flag = bytes.fromhex(decrypt(ciphertext))
if(b'crypto{' in flag):
print(flag)
Flag: crypto{k3y5__r__n07__p455w0rdz?}
ECB CBC WTF
Here you can encrypt in CBC but only decrypt in ECB. That shouldn't be a weakness because they're different modes... right?
Flag được mã hóa bằng AES_CBC, tuy nhiên giải mã lại là AES_ECB. Nghe có vẻ khá chuối.
Ở đây, mình để ý ciphertext = iv.hex() + encrypted.hex(), vì vậy 32 kí tự hex đầu chính là iv. Dựa vào iv đó, mình sẽ giải mã CBC với iv và phương thức decrypt là ECB. Dưới đây là code thực hiện:
ECB is the most simple mode, with each plaintext block encrypted entirely independently. In this case, your input is prepended to the secret flag and encrypted and that's it. We don't even provide a decrypt function. Perhaps you don't need a padding oracle when you have an "ECB oracle"?
from Crypto.Cipher import AES
import requests
from tqdm import tqdm
flag = 'crypto{'
def encrypt(string):
url = "https://aes.cryptohack.org/ecb_oracle/encrypt/"
url += str(string.encode().hex()) + "/"
r = requests.get(url)
js = r.json()
return js["ciphertext"]
count = 15
for i in range(0,64,32):
while(True):
payload= "0" * (count-len(flag))
res1 = encrypt(payload)
for j in tqdm("abcdefghijklmnopqrstuvwxyz0123456789_{}"):
res2 = encrypt(payload + flag + j)
if(res1[i:i+32] == res2[i:i+32]):
flag += j
break
if(len(flag) in [15, 31, 47]):
count += 16
break
print(flag)
Flag: crypto{p3n6u1n5_h473_3cb}
FLIPPING COOKIE
You can get a cookie for my website, but it won't help you read the flag... I think.
source.py
from Crypto.Cipher import AES
import os
from Crypto.Util.Padding import pad, unpad
from datetime import datetime, timedelta
KEY = ?
FLAG = ?
@chal.route('/flipping_cookie/check_admin/<cookie>/<iv>/')
def check_admin(cookie, iv):
cookie = bytes.fromhex(cookie)
iv = bytes.fromhex(iv)
try:
cipher = AES.new(KEY, AES.MODE_CBC, iv)
decrypted = cipher.decrypt(cookie)
unpadded = unpad(decrypted, 16)
except ValueError as e:
return {"error": str(e)}
if b"admin=True" in unpadded.split(b";"):
return {"flag": FLAG}
else:
return {"error": "Only admin can read the flag"}
@chal.route('/flipping_cookie/get_cookie/')
def get_cookie():
expires_at = (datetime.today() + timedelta(days=1)).strftime("%s")
cookie = f"admin=False;expiry={expires_at}".encode()
iv = os.urandom(16)
padded = pad(cookie, 16)
cipher = AES.new(KEY, AES.MODE_CBC, iv)
encrypted = cipher.encrypt(padded)
ciphertext = iv.hex() + encrypted.hex()
return {"cookie": ciphertext}
Để ý ciphertext = iv.hex() + encrypted.hex() nên ta sẽ tìm ra được iv. VIệc đó tính sau, giờ hãy nhìn vào hàm check_admin. Sau khi giải mã, nếu trong cookie có admin=True thì mới trả về flag. Vậy phải làm như nào ta.
Do yếu tố liên quan tới admin nằm ở trong block đầu tiên, thứ mà mình có thể kiểm soát thông qua IV. Ở đây mình sẽ có như sau:
Data Encryption Standard was the forerunner to AES, and is still widely used in some slow-moving areas like the Payment Card Industry. This challenge demonstrates a strange weakness of DES which a secure block cipher should not have.
source.py
from Crypto.Cipher import DES3
from Crypto.Util.Padding import pad
IV = os.urandom(8)
FLAG = ?
def xor(a, b):
# xor 2 bytestrings, repeating the 2nd one if necessary
return bytes(x ^ y for x,y in zip(a, b * (1 + len(a) // len(b))))
@chal.route('/triple_des/encrypt/<key>/<plaintext>/')
def encrypt(key, plaintext):
try:
key = bytes.fromhex(key)
plaintext = bytes.fromhex(plaintext)
plaintext = xor(plaintext, IV)
cipher = DES3.new(key, DES3.MODE_ECB)
ciphertext = cipher.encrypt(plaintext)
ciphertext = xor(ciphertext, IV)
return {"ciphertext": ciphertext.hex()}
except ValueError as e:
return {"error": str(e)}
@chal.route('/triple_des/encrypt_flag/<key>/')
def encrypt_flag(key):
return encrypt(key, pad(FLAG.encode(), 8).hex())
Nghĩa là chỉ cần mã hóa message 2 lần bằng Weak Key, ta sẽ nhận lại chính message.
Áp dụng vào bài, mình sẽ thử dùng từng tổ hợp cặp khóa cho tới khi ra flag.