Path: blob/master/Message-Authentication-Code/Attack-Length-Extension-CBC-MAC/CBC-Length-Extension.py
1402 views
'''-----------------------------<Server-Side>-------------------------------'''1from Crypto.Util.number import *2from Crypto.Cipher import AES34# Secret values not known to the attacker5from key import AES_key, MAC_flag67AES_key = AES_key.decode("hex")8iv = "\x00" * 169BLOCKSIZE = 161011def MAC_generation(plaintext):12try:13assert len(plaintext) % 16 == 01415# Does not allow to generate MAC of the below plaintext16if plaintext == "Check length extension attack!!!":17print("Not allowed to calculate MAC of this string!")18exit()1920obj1 = AES.new(AES_key, AES.MODE_CBC, iv)21ciphertext = obj1.encrypt(plaintext)22ciphertext = ciphertext[len(ciphertext) - 16:]2324return ciphertext.encode("hex")25except:26print "Invalid Input"2728def MAC_authentication(auth_tag):29if auth_tag == MAC_flag:30print "Successful Exploit!"31else:32print "Exploit Failed!"33'''----------------------------</Server-Side>--------------------------------'''3435'''---------------------------<Attacker-Side>--------------------------------'''36def xor_strings(s1, s2):37assert len(s1) == len(s2)38ct = "".join([chr(ord(s1[i]) ^ ord(s2[i])) for i in range(len(s1))])39return ct404142def exploit():43target_string = "Check length extension attack!!!"44assert len(target_string) == 324546'''Direct Check: Calling the MAC_generation function by passing47target_string as the parameter directly --> Not allowed by the server'''48MAC_generation(target_string)4950# Exploit to bypass the plaintext check filter51print "\n\nThe exploit!!"52first_slice = target_string[:16]5354'''We are allowed to give input to the server, hence calling the55MAC_generation function for illustration'''56MAC_first_slice = MAC_generation(first_slice).decode("hex")57# MAC_target_string = MAC(MAC(target_string[:16]) xor target_string[16:32])58second_slice = xor_strings(MAC_first_slice, target_string[16:32])59MAC_target_string = MAC_generation(second_slice)60# Calling the MAC_authentication function to illustrate authentication61MAC_authentication(MAC_target_string)6263if __name__ == '__main__':64exploit()65'''---------------------------</Attacker-Side>-------------------------------'''666768