Hash长度扩展攻击

Hash长度扩展攻击

很早之前蓝鲸ctf的时候就遇到了hash扩展长度攻击的问题,当时没有整理,趁把这道题放夏令营的时候整理一下

<?php 
//$flag and $secret in flag.php and strlen($secret)==15
include("flag.php");
if(!isset($_POST['username'])){show_source(__FILE__);die();}
$username = $_POST["username"];
$password = $_POST["password"];

    if (!empty($_COOKIE["getmein"])) {

    if (urldecode($username) === "admin" && urldecode($password) != "admin") {
    if ($_COOKIE["getmein"] === md5($secret . urldecode($username . $password))) {
        echo "Congratulations! You are a registered user.\n";
        die ("The flag is ". $flag);
    }
    else {
        die ("Your cookies don't match up! STOP HACKING THIS SITE.");
    }
}
else {
    die ("You are not an admin! LEAVE.");
}
}

setcookie("sample-hash", md5($secret . urldecode("admin" . "admin")), time() + (60 * 60 * 24 * 7));

if (empty($_COOKIE["source"])) {
    setcookie("source", 0, time() + (60 * 60 * 24 * 7));
}
else {
if ($_COOKIE["source"] != 0) {
    echo ""; // This source code is outputted here
}
}

我们已知的是:

md5($secret.adminadmin)= 2aba05712564dde4fb15fdb5f0e0de66;
以及$secret的长度为15;  

我们要得到的是如何构造一个$password让

md5($secret . urldecode($username . $password)))已知,并构造cookie;  

此处我们并不知道$secret的值是什么,password又不能等于admin,所以我们需要用到hash长度扩展攻击;相当于是现在我们不知道字符串是什么。只知道其长度,通过hash长度拓展攻击,我们可以得到在原字符串的基础上进行了补位以及添加新字符串的hash值

原理

首先,当hash函数拿到需要被hash的字符串后,先将其字节长度整除64,取得余数。如果该余数正好等于56,那么就在该字符串最后添加上8个字节的长度描述符(具体用bit表示)。如果不等于56,就先对字符串进行长度填充,填充时第一个字节为hex(80),其他字节均用hex(00)填充,填充至余数为56后,同样增加8个字节的长度描述符(该长度描述符为需要被hash的字符串的长度,不是填充之后整个字符串的长度)。以上过程,称之为补位。

补位完成后,字符串以64位一组进行分组(因为上面的余数为56,加上8个字节的长度描述符后,正好是64位,凑成一组)。字符串能被分成几组就会进行多少次“复杂的数学变化”。每次进行“复杂的数学变化”都会生成一组新的registers值供下一次“复杂的数学变化”来调用。第一次“复杂的数学变化”会调用程序中的默认值。当后面已经没有分组可以进行数学变化时,该组生成的registers值就是最后的hash值。

(原理原文链接:www.freebuf.com/articles/web/69264.html)

也就是说我们先对$secret.adminadmin进行补位,然后添加一个新的字符串,用补位完成后那个分组生成的register值对新添加的字符串进性运算得到最后的hash值,而补位完成后那个分组的register值和我们已知的md5($secret.adminadmin)值相等。

hashpump

HashPump是一个借助于OpenSSL实现了针对多种散列函数的攻击的工具,支持针对MD5、CRC32、SHA1、SHA256和SHA512等长度扩展攻击。而MD2、SHA224和SHA384算法不受此攻击的影响。

安装

git clone https://github.com/bwall/HashPump
apt-get install g++ libssl-dev
cd HashPump
make
make install

所需数据

root@ubuntu:~/HashPump# hashpump
Input Signature: 2aba05712564dde4fb15fdb5f0e0de66//hash值
Input Data: adminadmin//加密的明文
Input Key Length: 15//key长度
Input Data to Add: 1
286d5b319a75f5f498dac9a52dcb360e//新生成的md5也就是getmein
adminadmin\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xc8\x00\x00\x00\x00\x00\x00\x001//admin.$passowrd
0%