Length extension attack exploits the message authentication code (MAC) which is used for authenticating a message.
What is Message Authentication Code (MAC)?
Message Authentication Code is similar to hashing but it also involves a secret key. This provides data integrity as well as authenticity to a message, unlike hashing which provides only data integrity. For calculating MAC, known hashing algorithms like MD5, SHA-1, SHA-2 are used along with a secret key which is shared between sender and receiver. The secret key K is appended with the message M and the hash H is calculated. Hash along with the original message is sent to the receiver. Receiver computes the hash H’ from the pre shared secret key K and received message M. It compares received hash H with computed hash H’. Message integrity and authenticity is preserved if H=H’.
How attack works?
The vulnerability lies in the way MAC is implemented. It is possible to calculate the hash of message M2 if attacker knows the message M1 and hash H1 without knowing the key. Attacker appends the message M2 to the message M1 (with appropriate padding) and calculates a new hash H2. This new hash H2 is the hash of the message (M1+M2). Thus attacker successfully calculates the hash of the new message containing his appended message M2 without knowing the secret key.
Implementing the attack
To implement the attack, following are required
- Original message
- Original Hash
- Custom message to append
- Key length
Knowledge of the internal working of different hashing algorithm is required so that appropriate padding can be appended before calculating the hash. This is a complex process. We will be using a python library hashpumpy to implement this attack.
Install the library using pip install hashpumpy. There might be error due to missing ssl library dependency, if so run apt-get install python-pip python-dev libssl-dev before installing hashpumpy.
Python code for length extension attack
hash,message = hashpumpy.hashpump(‘Know Hash (H1)’, ‘Known Message (M1)’, ‘Message to append (M2)’, KeyLength)
Output of the function hashpump is a tuple which consisting of new hash H2 and its corresponding message M1+M2
Hashing algorithms like MD5, SHA-1 and SHA-2 are vulnerable to length extension attack. SHA-3 is safe and not suseptible to the attack. Use HMAC instead of MAC for message authentication.
I hope this article was informative. Do comment your suggestions about the post. I will be happy to receive the feedback. Also share if you find it useful.
Follow me on twitter @PiyushSaurabh07 to get the notifications of my new posts in future.
Happy Learning 🙂
The author is a security engineer with interest in cloud technologies, application development and DevOps.