Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

变量名混淆 #871

Open
guanhui07 opened this issue Dec 21, 2024 · 0 comments
Open

变量名混淆 #871

guanhui07 opened this issue Dec 21, 2024 · 0 comments
Labels

Comments

@guanhui07
Copy link
Owner

guanhui07 commented Dec 21, 2024

接上篇 抽象语法树

-做变量名混淆

<?php

namespace App\Helper;

use Exception;
use PhpParser\NodeVisitorAbstract;
use PhpParser\NodeTraverser;
use PhpParser\ParserFactory;
use PhpParser\PrettyPrinter;


class VariableRenamer extends NodeVisitorAbstract
{
    private $variableMap = [];

    public static function new()
    {
        return new self();
    }

    /**
     * @param $codePath string
     */
    public function getParse(string $codePath)
    {
        $code = file_get_contents($codePath); // 替换成实际要混淆的PHP文件路径

        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
        try {
            $ast = $parser->parse($code);
            $newAst = $this->newAst($ast);
        } catch (Exception $e) {
            echo "Parse error: {$e->getMessage()}\n";
            exit(1);
        }

        $printer = new PrettyPrinter\Standard();
        $obfuscatedCode = $printer->prettyPrintFile($newAst);
        echo $obfuscatedCode;
        return $obfuscatedCode;

    }
    public function enterNode(\PhpParser\Node $node)
    {
        if ($node instanceof \PhpParser\Node\Expr\Variable) {
            $oldName = $node->name;
            if (!isset($this->variableMap[$oldName])) {
                var_dump($oldName);
                $newName = md5($oldName); // 简单用MD5值来作为新变量名示例,实际可更合理生成
                $newName = 'var'.$newName;
                $this->variableMap[$oldName] = $newName;

            }
            $node->name = $this->variableMap[$oldName];
        }
        return $node;
    }
    public function newAst($ast)
    {
        $traverser = new NodeTraverser();
        $renamer = new VariableRenamer();
        $traverser->addVisitor($renamer);
        $newAst = $traverser->traverse($ast);
        return $newAst;
    }
}

基本混淆思路与代码示例
解析 PHP 代码:
利用php-parser的Parser类来将 PHP 代码解析成抽象语法树(AST)。
遍历并修改抽象语法树(进行混淆操作):
这里可以进行多种混淆方式,比如重命名变量、函数名等

还可以做类似的 方法名 混淆
一定程度上增加代码阅读难度来保护知识产权等
代码混淆也不能完全保证代码不被逆向分析,只是增加一定成本而已。

需要真正的加密

https://doc.swoole.com/@compiler/compiler.html 韩天峰的

链接

https://github.com/nikic/PHP-Parser

@guanhui07 guanhui07 added the php label Dec 21, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant