如何正则表达式匹配和正则表达式替换PHP中的字符串

时间:2017-08-14 13:06:06

标签: php regex deobfuscation

我有一段混淆的代码,我想恢复正常。

我想出了一个简单的preg_replace_callback()和一个preg_match()嵌套在其中的替代品。

由于某些原因我的代码不想匹配,特别是回调中的preg_match

以下是我的代码片段。

在我的debbuging中preg_match_all()的数组(我已经尝试了常规preg_match())返回空,尽管它在回调之外工作。

<?php
$code = '
public function encrypt($UDw2y33pQ_22) { 
        goto eKGyEfM327pq; 
    YlzBCxTNCJzo: 
        $p7nCDJiybOtp = mcrypt_create_iv($I9ryzFUJtil4, 
    MCRYPT_RAND); 
        goto zqGNmmifhK7G; 
    eKGyEfM327pq: 
        $IE19PrOpdkbJ = "*97@$S8&8&*as&*SA7sa*SA7alnIU&7#$%gf^IsPj8"; 
        goto uR63Cxb5ZtRs; 
    uR63Cxb5ZtRs: 
        $I9ryzFUJtil4 = mcrypt_get_iv_size(MCRYPT_BLOWFISH, 
    MCRYPT_MODE_ECB); 
        goto YlzBCxTNCJzo; 
    TdHsUlVktK5b: 
        return base64_encode($pcLABic8Iiv1); 
        goto XJlxnac4pgAr; 
    zqGNmmifhK7G: 
        $pcLABic8Iiv1 = mcrypt_encrypt(MCRYPT_BLOWFISH, $IE19PrOpdkbJ, utf8_encode($UDw2y33pQ_22), MCRYPT_MODE_ECB, $p7nCDJiybOtp); 
        goto TdHsUlVktK5b; 
    XJlxnac4pgAr: 
}';
$deobfuscated = preg_replace_callback("/goto ([a-zA-Z0-9_]+);/", function($match){
    preg_match_all("/({$match[1]}:)((\s|\S)*?)([a-zA-Z0-9]{12}:)/ms", $code, $a);
    return $a[0][2];
},$code);

echo $deobfuscated;

实际结果:

public function encrypt($UDw2y33pQ_22) { 

YlzBCxTNCJzo: 
    $p7nCDJiybOtp = mcrypt_create_iv($I9ryzFUJtil4, MCRYPT_RAND); 

eKGyEfM327pq: 
    $IE19PrOpdkbJ = "*97@$S8&8&*as&*SA7sa*SA7alnIU&7#$%gf^IsPj8"; 

uR63Cxb5ZtRs: 
    $I9ryzFUJtil4 = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB); 

TdHsUlVktK5b: 
    return base64_encode($pcLABic8Iiv1); 

zqGNmmifhK7G: 
    $pcLABic8Iiv1 = mcrypt_encrypt(MCRYPT_BLOWFISH, $IE19PrOpdkbJ, utf8_encode($UDw2y33pQ_22), MCRYPT_MODE_ECB, $p7nCDJiybOtp); 

XJlxnac4pgAr: 
}

预期结果:

public function encrypt($UDw2y33pQ_22) { 
    $IE19PrOpdkbJ = "*97@$S8&8&*as&*SA7sa*SA7alnIU&7#$%gf^IsPj8"; 
    $I9ryzFUJtil4 = mcrypt_get_iv_size(MCRYPT_BLOWFISH, MCRYPT_MODE_ECB); 
    $p7nCDJiybOtp = mcrypt_create_iv($I9ryzFUJtil4, MCRYPT_RAND); 
    $pcLABic8Iiv1 = mcrypt_encrypt(MCRYPT_BLOWFISH, $IE19PrOpdkbJ, utf8_encode($UDw2y33pQ_22), MCRYPT_MODE_ECB, $p7nCDJiybOtp); 
    return base64_encode($pcLABic8Iiv1);
}

1 个答案:

答案 0 :(得分:2)

闭包内未定义

$code。您需要通过use声明传递它。例如:

$deobfuscated = preg_replace_callback("/goto ([a-zA-Z0-9_]+);/", function($match) use ($code) {
    preg_match_all("/({$match[1]}:)((\s|\S)*?)([a-zA-Z0-9]{12}:)/ms", $code, $a);
    return $a[0][2];
},$code);

在尝试返回$a[0][2]之前,您还应检查现有密钥。