├── .github └── workflows │ ├── build-macos.yml │ ├── build-ubuntu.yml │ ├── build-windows.yml │ ├── codeql-analysis.yml │ ├── release-agent.yml │ ├── update-test-agent.yml │ └── vul-test.yml ├── .gitignore ├── CHANGELOG.md ├── CHANGELOG_CN.md ├── CONTRIBUTING.md ├── LICENSE ├── MANIFEST.in ├── README.ZH_CN.md ├── README.md ├── dongtai_agent_python ├── __init__.py ├── api │ ├── __init__.py │ └── openapi.py ├── assess │ ├── __init__.py │ ├── c_api_hook.py │ ├── common_hook.py │ ├── ctypes_hook.py │ └── patch.py ├── assess_ext │ ├── .gitignore │ ├── c_api.c │ ├── funchook │ │ ├── .ci │ │ │ ├── Dockerfile-alpine-test │ │ │ └── run-cmake-test.sh │ │ ├── .dockerignore │ │ ├── .github │ │ │ └── workflows │ │ │ │ ├── run-tests.yml │ │ │ │ └── upload-assets-on-pushing-tag.yml │ │ ├── .gitignore │ │ ├── .gitmodules │ │ ├── CMakeLists.txt │ │ ├── LICENSE │ │ ├── README.md │ │ ├── cmake │ │ │ ├── aarch64-linux-gnu.cmake │ │ │ ├── capstone.cmake.in │ │ │ ├── i686-w64-mingw32.cmake │ │ │ └── x86_64-w64-mingw32.cmake │ │ ├── distorm │ │ │ ├── .github │ │ │ │ └── workflows │ │ │ │ │ └── py.yml │ │ │ ├── .gitignore │ │ │ ├── COPYING │ │ │ ├── MANIFEST.in │ │ │ ├── README.md │ │ │ ├── disOps │ │ │ │ ├── disOps.py │ │ │ │ ├── registers.py │ │ │ │ ├── x86db.py │ │ │ │ ├── x86generator.py │ │ │ │ ├── x86header.py │ │ │ │ └── x86sets.py │ │ │ ├── examples │ │ │ │ ├── cs │ │ │ │ │ ├── TestdiStorm │ │ │ │ │ │ ├── Program.cs │ │ │ │ │ │ ├── Properties │ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ │ └── TestdiStorm.csproj │ │ │ │ │ ├── distorm-net.sln │ │ │ │ │ ├── distorm-net │ │ │ │ │ │ ├── CodeInfo.cs │ │ │ │ │ │ ├── DecodedInst.cs │ │ │ │ │ │ ├── DecodedResult.cs │ │ │ │ │ │ ├── DecomposedInst.cs │ │ │ │ │ │ ├── DecomposedResult.cs │ │ │ │ │ │ ├── Opcodes.cs │ │ │ │ │ │ ├── Opcodes.tt │ │ │ │ │ │ ├── Operand.cs │ │ │ │ │ │ ├── Properties │ │ │ │ │ │ │ └── AssemblyInfo.cs │ │ │ │ │ │ ├── diStorm3.cs │ │ │ │ │ │ └── distorm-net.csproj │ │ │ │ │ └── readme │ │ │ │ ├── ddk │ │ │ │ │ ├── README │ │ │ │ │ ├── distorm.ini │ │ │ │ │ ├── dummy.c │ │ │ │ │ ├── main.c │ │ │ │ │ ├── makefile │ │ │ │ │ └── sources │ │ │ │ ├── java │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── distorm │ │ │ │ │ │ ├── .classpath │ │ │ │ │ │ ├── .project │ │ │ │ │ │ ├── .settings │ │ │ │ │ │ │ └── org.eclipse.jdt.core.prefs │ │ │ │ │ │ └── src │ │ │ │ │ │ │ ├── Main.java │ │ │ │ │ │ │ └── diStorm3 │ │ │ │ │ │ │ ├── CodeInfo.java │ │ │ │ │ │ │ ├── DecodedInst.java │ │ │ │ │ │ │ ├── DecodedResult.java │ │ │ │ │ │ │ ├── DecomposedInst.java │ │ │ │ │ │ │ ├── DecomposedResult.java │ │ │ │ │ │ │ ├── OpcodeEnum.java │ │ │ │ │ │ │ ├── Opcodes.java │ │ │ │ │ │ │ ├── Operand.java │ │ │ │ │ │ │ └── distorm3.java │ │ │ │ │ ├── jdistorm.c │ │ │ │ │ ├── jdistorm.h │ │ │ │ │ ├── jdistorm.sln │ │ │ │ │ └── jdistorm.vcproj │ │ │ │ ├── linux │ │ │ │ │ ├── Makefile │ │ │ │ │ └── main.c │ │ │ │ ├── tests │ │ │ │ │ ├── Makefile │ │ │ │ │ ├── main.cpp │ │ │ │ │ ├── tests.sln │ │ │ │ │ ├── tests.vcxproj │ │ │ │ │ └── tests.vcxproj.filters │ │ │ │ └── win32 │ │ │ │ │ ├── disasm.sln │ │ │ │ │ ├── disasm.vcxproj │ │ │ │ │ ├── disasm.vcxproj.filters │ │ │ │ │ └── main.cpp │ │ │ ├── include │ │ │ │ ├── distorm.h │ │ │ │ └── mnemonics.h │ │ │ ├── make │ │ │ │ ├── linux │ │ │ │ │ └── Makefile │ │ │ │ ├── mac │ │ │ │ │ └── Makefile │ │ │ │ ├── tinycc │ │ │ │ │ └── Makefile │ │ │ │ └── win32 │ │ │ │ │ ├── cdistorm.vcxproj │ │ │ │ │ ├── cdistorm.vcxproj.filters │ │ │ │ │ ├── distorm.sln │ │ │ │ │ ├── resource.h │ │ │ │ │ └── resource.rc │ │ │ ├── python │ │ │ │ ├── distorm3 │ │ │ │ │ ├── __init__.py │ │ │ │ │ ├── __main__.py │ │ │ │ │ └── _generated.py │ │ │ │ ├── python_module_init.c │ │ │ │ └── test_distorm3.py │ │ │ ├── setup.cfg │ │ │ ├── setup.py │ │ │ ├── src │ │ │ │ ├── config.h │ │ │ │ ├── decoder.c │ │ │ │ ├── decoder.h │ │ │ │ ├── distorm.c │ │ │ │ ├── instructions.c │ │ │ │ ├── instructions.h │ │ │ │ ├── insts.c │ │ │ │ ├── insts.h │ │ │ │ ├── mnemonics.c │ │ │ │ ├── operands.c │ │ │ │ ├── operands.h │ │ │ │ ├── prefix.c │ │ │ │ ├── prefix.h │ │ │ │ ├── textdefs.c │ │ │ │ ├── textdefs.h │ │ │ │ ├── wstring.h │ │ │ │ └── x86defs.h │ │ │ └── test-deps │ │ │ │ └── yasm-1.3.0-win64.exe │ │ ├── include │ │ │ └── funchook.h │ │ ├── src │ │ │ ├── cmake_config.h.in │ │ │ ├── disasm.h │ │ │ ├── disasm_Zydis.c │ │ │ ├── disasm_capstone.c │ │ │ ├── disasm_distorm.c │ │ │ ├── funchook.c │ │ │ ├── funchook_arm64.c │ │ │ ├── funchook_arm64.h │ │ │ ├── funchook_internal.h │ │ │ ├── funchook_unix.c │ │ │ ├── funchook_windows.c │ │ │ ├── funchook_x86.c │ │ │ └── funchook_x86.h │ │ └── test │ │ │ ├── CMakeLists.txt │ │ │ ├── libfunchook_test.c │ │ │ ├── libfunchook_test_aarch64_gas.S │ │ │ ├── libfunchook_test_x86_64_gas.S │ │ │ ├── libfunchook_test_x86_64_masm.asm │ │ │ ├── libfunchook_test_x86_gas.S │ │ │ ├── libfunchook_test_x86_masm.asm │ │ │ ├── suffix.list │ │ │ ├── test_main.c │ │ │ └── x86_test.S │ ├── include │ │ ├── logger.h │ │ ├── patch.h │ │ └── utils.h │ ├── logger.c │ ├── patch.c │ └── patch │ │ ├── cast.c │ │ ├── concat.c │ │ ├── str_cformat.c │ │ └── str_fstring.c ├── cli │ ├── __init__.py │ └── run.py ├── common │ └── logger.py ├── config-example.json ├── context │ ├── __init__.py │ ├── request.py │ ├── request_context.py │ └── tracker.py ├── middlewares │ ├── __init__.py │ ├── base_middleware.py │ ├── django_middleware.py │ ├── django_wsgi_middleware.py │ ├── flask_middleware.py │ ├── flask_wsgi_middleware.py │ └── wsgi_middleware.py ├── policy │ ├── __init__.py │ ├── deal_data.py │ ├── policy.py │ └── tracking.py ├── policy_api.json ├── setting │ ├── __init__.py │ ├── config.py │ ├── const.py │ └── setting.py ├── tests │ ├── __init__.py │ ├── policy │ │ ├── __init__.py │ │ ├── test_policy.py │ │ └── test_tracking.py │ ├── setting │ │ ├── __init__.py │ │ └── test_setting.py │ ├── utils │ │ ├── __init__.py │ │ ├── test_scope.py │ │ ├── test_singleton.py │ │ └── test_utils.py │ └── vul-test.sh ├── utils │ ├── __init__.py │ ├── scope.py │ ├── singleton.py │ ├── system_info.py │ └── utils.py └── version.py ├── scripts └── dongtai-cli ├── setup.cfg └── setup.py /.github/workflows/build-macos.yml: -------------------------------------------------------------------------------- 1 | name: Build macOS 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | setup: 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | os: [ "macos-latest" ] 18 | python-version: [ "3.6" ] 19 | 20 | steps: 21 | - name: Clone Repository 22 | uses: actions/checkout@v2 23 | 24 | - name: Install packages 25 | run: | 26 | brew install cmake 27 | 28 | - name: Set up Python ${{ matrix.python-version }} 29 | uses: actions/setup-python@v2 30 | with: 31 | python-version: ${{ matrix.python-version }} 32 | 33 | - name: Build and Install Agent 34 | run: | 35 | pip install --user --upgrade pip setuptools 36 | pip install --user . -v 37 | pip show dongtai_agent_python 38 | -------------------------------------------------------------------------------- /.github/workflows/build-ubuntu.yml: -------------------------------------------------------------------------------- 1 | name: Build Ubuntu 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | setup: 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | os: [ "ubuntu-20.04" ] 18 | python-version: [ "3.6" ] 19 | 20 | steps: 21 | - name: Clone Repository 22 | uses: actions/checkout@v2 23 | 24 | - name: Install packages 25 | run: | 26 | sudo apt update 27 | sudo apt install -y gcc make cmake 28 | 29 | - name: Set up Python ${{ matrix.python-version }} 30 | uses: actions/setup-python@v2 31 | with: 32 | python-version: ${{ matrix.python-version }} 33 | 34 | - name: Build and Install Agent 35 | run: | 36 | pip install --user --upgrade pip setuptools 37 | pip install --user . -v 38 | pip show dongtai_agent_python 39 | -------------------------------------------------------------------------------- /.github/workflows/build-windows.yml: -------------------------------------------------------------------------------- 1 | name: Build Windows 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | setup: 13 | runs-on: ${{ matrix.os }} 14 | strategy: 15 | fail-fast: false 16 | matrix: 17 | os: [ "windows-latest" ] 18 | python-version: [ "3.6" ] 19 | 20 | steps: 21 | - name: Clone Repository 22 | uses: actions/checkout@v2 23 | 24 | - name: Install Visual Studio 25 | uses: microsoft/setup-msbuild@v1.1 26 | with: 27 | msbuild-architecture: x64 28 | 29 | - name: Set up Python ${{ matrix.python-version }} 30 | uses: actions/setup-python@v2 31 | with: 32 | python-version: ${{ matrix.python-version }} 33 | 34 | - name: Install packages 35 | run: | 36 | pip install cmake 37 | 38 | - name: Build and Install Agent 39 | run: | 40 | pip install --user --upgrade pip setuptools 41 | pip install --user . -v 42 | pip show dongtai_agent_python 43 | -------------------------------------------------------------------------------- /.github/workflows/codeql-analysis.yml: -------------------------------------------------------------------------------- 1 | 2 | name: "Code Scanning - Action" 3 | 4 | on: 5 | push: 6 | branches: [ master ] 7 | paths-ignore: 8 | - '.github/**' 9 | - '**.md' 10 | - '**.yml' 11 | - '**.json' 12 | - 'LICENSE' 13 | - '.gitignore' 14 | pull_request: 15 | branches: [ master ] 16 | paths-ignore: 17 | - '.github/**' 18 | - '**.md' 19 | - '**.yml' 20 | - '**.json' 21 | - 'LICENSE' 22 | - '.gitignore' 23 | schedule: 24 | # ┌───────────── minute (0 - 59) 25 | # │ ┌───────────── hour (0 - 23) 26 | # │ │ ┌───────────── day of the month (1 - 31) 27 | # │ │ │ ┌───────────── month (1 - 12 or JAN-DEC) 28 | # │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT) 29 | # │ │ │ │ │ 30 | # │ │ │ │ │ 31 | # │ │ │ │ │ 32 | # * * * * * 33 | - cron: '30 1 * * 0' 34 | 35 | jobs: 36 | CodeQL-Build: 37 | # If you're only analyzing JavaScript or Python, CodeQL runs on ubuntu-latest, windows-latest, and macos-latest. 38 | # If you're analyzing C/C++, C#, Go, or Java, CodeQL runs on ubuntu-latest, windows-2019, and macos-latest. 39 | runs-on: ubuntu-latest 40 | 41 | permissions: 42 | # required for all workflows 43 | security-events: write 44 | 45 | # only required for workflows in private repositories 46 | actions: read 47 | contents: read 48 | 49 | steps: 50 | - name: Checkout repository 51 | uses: actions/checkout@v2 52 | 53 | # Initializes the CodeQL tools for scanning. 54 | - name: Initialize CodeQL 55 | uses: github/codeql-action/init@v1 56 | # Override language selection by uncommenting this and choosing your languages 57 | with: 58 | languages: python 59 | 60 | - name: Set up Python 61 | uses: actions/setup-python@v2 62 | with: 63 | python-version: "3.9" 64 | 65 | - name: Package 66 | run: | 67 | cp dongtai_agent_python/config-example.json dongtai_agent_python/config.json 68 | python setup.py sdist 69 | 70 | - name: Perform CodeQL Analysis 71 | uses: github/codeql-action/analyze@v1 -------------------------------------------------------------------------------- /.github/workflows/release-agent.yml: -------------------------------------------------------------------------------- 1 | name: Release Agent 2 | 3 | on: 4 | release: 5 | types: 6 | - published 7 | 8 | jobs: 9 | build: 10 | 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: read 14 | packages: write 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: "3.9" 22 | 23 | - name: Get release 24 | id: get_release 25 | uses: bruceadams/get-release@v1.2.2 26 | env: 27 | GITHUB_TOKEN: ${{ github.token }} 28 | 29 | - name: Get python version 30 | id: get_python_version 31 | run: | 32 | V=`echo ${{ steps.get_release.outputs.tag_name }} | sed -e's/v//g' | sed -e's/V//g'`; \ 33 | echo ::set-output name=VERSION::${V} 34 | 35 | - name: Generate version file 36 | run: | 37 | cd ${{ github.workspace }} && \ 38 | echo "${{ github.event.repository.name }},version,${{ steps.get_python_version.outputs.VERSION }}" >> version.txt && \ 39 | echo "${{ github.event.repository.name }},commit_hash,${GITHUB_SHA}" >> version.txt 40 | 41 | - name: Upload version file to oss 42 | id: upload_version_file_to_oss 43 | uses: tvrcgo/upload-to-oss@master 44 | with: 45 | key-id: ${{ secrets.OSS_KEY_ID }} 46 | key-secret: ${{ secrets.OSS_KEY_SECRET }} 47 | region: oss-cn-beijing 48 | bucket: huoqi-public 49 | assets: | 50 | ./version.txt:/iast/release-version/${{ github.event.repository.name }}/${{ steps.get_python_version.outputs.VERSION }}/version.txt 51 | 52 | - name: Package 53 | run: | 54 | cp dongtai_agent_python/config-example.json dongtai_agent_python/config.json 55 | python setup.py sdist 56 | 57 | - uses: manyuanrong/setup-ossutil@v2.0 58 | with: 59 | endpoint: "oss-cn-beijing.aliyuncs.com" 60 | access-key-id: ${{ secrets.OSS_KEY_ID }} 61 | access-key-secret: ${{ secrets.OSS_KEY_SECRET }} 62 | 63 | - name: Publish 64 | run: | 65 | filename=$(python setup.py --fullname) 66 | ossutil cp -rf dist/${filename}.tar.gz oss://dongtai/agent/python/dongtai_agent_python.tar.gz --meta x-oss-object-acl:public-read 67 | -------------------------------------------------------------------------------- /.github/workflows/update-test-agent.yml: -------------------------------------------------------------------------------- 1 | name: Update Test Agent 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | build: 10 | if: github.event_name == 'push' 11 | runs-on: ubuntu-latest 12 | permissions: 13 | contents: read 14 | packages: write 15 | 16 | steps: 17 | - uses: actions/checkout@v2 18 | - name: Set up Python 19 | uses: actions/setup-python@v2 20 | with: 21 | python-version: "3.9" 22 | 23 | - name: Package 24 | run: | 25 | cp dongtai_agent_python/config-example.json dongtai_agent_python/config.json 26 | python setup.py sdist 27 | 28 | - uses: manyuanrong/setup-ossutil@v2.0 29 | with: 30 | endpoint: "oss-cn-beijing.aliyuncs.com" 31 | access-key-id: ${{ secrets.OSS_KEY_ID }} 32 | access-key-secret: ${{ secrets.OSS_KEY_SECRET }} 33 | 34 | 35 | - name: Publish 36 | run: | 37 | filename=$(python setup.py --fullname) 38 | ossutil cp -rf dist/${filename}.tar.gz oss://dongtai/agent_test/python/dongtai_agent_python.tar.gz --meta x-oss-object-acl:public-read 39 | 40 | - name: Trigger Openapi Workflow 41 | uses: benc-uk/workflow-dispatch@v1 42 | with: 43 | workflow: Deploy DongTai OpenAPI To AWS 44 | token: ${{ secrets.BIDAYA0_PAT_FOR_OPENAPI }} 45 | ref: main 46 | repo: HXSecurity/DongTai-openapi 47 | -------------------------------------------------------------------------------- /.github/workflows/vul-test.yml: -------------------------------------------------------------------------------- 1 | name: Vul Test 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | pull_request: 8 | branches: 9 | - master 10 | 11 | jobs: 12 | build: 13 | 14 | runs-on: ubuntu-latest 15 | 16 | steps: 17 | - name: Clone Repository 18 | uses: actions/checkout@v2 19 | with: 20 | path: DongTai-agent-python 21 | - name: Clone Vul Repository 22 | uses: actions/checkout@v2 23 | with: 24 | repository: jinghao1/DockerVulspace 25 | ref: main 26 | path: DockerVulspace 27 | 28 | - name: Set up Python 29 | uses: actions/setup-python@v2 30 | with: 31 | python-version: "3.9" 32 | 33 | - name: Prepare Agent code 34 | run: | 35 | cp -r ${{ github.workspace }}/DongTai-agent-python ${{ github.workspace }}/DockerVulspace/DongTai-agent-python 36 | 37 | - name: Prepare Agent Config 38 | shell: python 39 | run: | 40 | import json 41 | example_filename = '${{ github.workspace }}/DockerVulspace/DongTai-agent-python/dongtai_agent_python/config-example.json' 42 | filename = '${{ github.workspace }}/DockerVulspace/DongTai-agent-python/dongtai_agent_python/config.json' 43 | with open(example_filename) as f: 44 | data = json.load(f) 45 | data['iast']['server']['token'] = '0f0025dff8311467f6da5b5109a469f1831aa782' 46 | data['iast']['server']['url'] = 'https://iast-test.huoxian.cn/openapi' 47 | with open(filename, 'w') as f: 48 | json.dump(data, f) 49 | 50 | - name: Run Vul Container 51 | env: 52 | PROJECT_VERSION: 'v1.0.${{ github.run_id }}' 53 | run: | 54 | cd ${{ github.workspace }}/DockerVulspace 55 | docker-compose up -d 56 | 57 | - name: Run Vul test 58 | run: | 59 | curl --fail --retry-delay 10 --retry 30 --retry-connrefused http://127.0.0.1:8003/api/django/demo/get_open?name=Data 60 | cd ${{ github.workspace }}/DockerVulspace 61 | docker-compose exec -T djangoweb python -V 62 | docker-compose exec -T djangoweb pip list 63 | docker-compose exec -T flaskweb python -V 64 | docker-compose exec -T flaskweb pip list 65 | docker-compose logs djangoweb flaskweb 66 | bash ${{ github.workspace }}/DongTai-agent-python/dongtai_agent_python/tests/vul-test.sh \ 67 | django http://127.0.0.1:8003/api/django ${{ github.run_id }} 68 | bash ${{ github.workspace }}/DongTai-agent-python/dongtai_agent_python/tests/vul-test.sh \ 69 | flask http://127.0.0.1:8003/api/flask ${{ github.run_id }} 70 | docker-compose logs djangoweb flaskweb 71 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.DS_Store 2 | .idea 3 | venv 4 | *.pyc 5 | __pycache__/ 6 | /build/ 7 | /dist 8 | /dongtai_agent_python.egg-info 9 | *.log 10 | config.json 11 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contribution Guide 2 | 3 | This project follows the [DongTai Contribution Guide](https://github.com/HXSecurity/DongTai/blob/main/CONTRIBUTING.md). 4 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include *.py 2 | include *.md 3 | include LICENSE 4 | include dongtai_agent_python/*.py 5 | include dongtai_agent_python/config.json 6 | include dongtai_agent_python/policy_api.json 7 | include dongtai_agent_python/api/*.py 8 | include dongtai_agent_python/assess/*.py 9 | include dongtai_agent_python/assess_ext/*.c 10 | recursive-include dongtai_agent_python/assess_ext/funchook * 11 | exclude dongtai_agent_python/assess_ext/funchook/bin/* 12 | recursive-exclude dongtai_agent_python/assess_ext/funchook/build * 13 | recursive-exclude dongtai_agent_python/assess_ext/funchook/distorm/.git * 14 | exclude dongtai_agent_python/assess_ext/funchook/lib/* 15 | include dongtai_agent_python/assess_ext/include/*.h 16 | include dongtai_agent_python/assess_ext/patch/*.c 17 | include dongtai_agent_python/cli/*.py 18 | include dongtai_agent_python/common/*.py 19 | include dongtai_agent_python/context/*.py 20 | include dongtai_agent_python/middlewares/*.py 21 | include dongtai_agent_python/policy/*.py 22 | include dongtai_agent_python/setting/*.py 23 | include dongtai_agent_python/utils/*.py 24 | include version.txt 25 | -------------------------------------------------------------------------------- /README.ZH_CN.md: -------------------------------------------------------------------------------- 1 | ## DongTai-agent-python 2 | 3 | [![dongtai-project](https://img.shields.io/github/v/release/HXSecurity/DongTai?label=DongTai)](https://github.com/HXSecurity/DongTai/releases) 4 | [![dongtai--agent--python](https://img.shields.io/github/v/release/HXSecurity/DongTai-agent-python?label=DongTai-agent-python)](https://github.com/HXSecurity/DongTai-agent-python/releases) 5 | 6 | - [English document](README.md) 7 | 8 | ## 项目介绍 9 | 10 | DongTai-agent-python 是 **洞态IAST** 针对 Python 应用开发的数据采集端。在 Python 应用中,通过改写方法和函数的方式采集所需数据,然后将数据发送至 11 | DongTai OpenAPI 服务,再由云端引擎处理数据判断是否存在安全漏洞。 12 | 13 | DongTai-agent-python 14 | 15 | - `dongtai_agent_python/api/` 将 agent 采集的数据上报至 DongTai OpenAPI 服务。 16 | - `dongtai_agent_python/assess/` 根据云端策略 hook python 方法。 17 | - `dongtai_agent_python/assess_ext/` 根据云端策略 hook cpython 底层方法。 18 | - `dongtai_agent_python/cli/` 控制 agent 版本的热更新。 19 | - `dongtai_agent_python/context/` 请求上下文和上下文跟踪。 20 | - `dongtai_agent_python/middleware/` 用于接入不同的 python 框架,目前支持 Django、Flask, 均以中间件方式引入。 21 | - `dongtai_agent_python/policy/` 策略规则及污点数据处理。 22 | - `dongtai_agent_python/setting/` Agent 配置. 23 | - `dongtai_agent_python/config.json` 用于配置 DongTai OpenAPI 服务地址、Token、项目名称等。 24 | 25 | ## 应用场景 26 | 27 | - DevOps流程 28 | - 上线前安全测试 29 | - 第三方组件管理 30 | - 代码审计 31 | - 0 Day挖掘 32 | 33 | ## 系统依赖 34 | 35 | * Python: >=3.6 36 | * CPython 37 | * 编译依赖 (Agent 版本 >= 1.1.4) 38 | * gcc (Linux/macOS) 39 | * make (Linux/macOS) 40 | * cmake >= 3.6 41 | * Visual Studio (Windows) 42 | * bash (Alpine Linux) 43 | * libc-dev (Alpine Linux) 44 | * linux-headers (Alpine Linux) 45 | * Web 框架 46 | * Django: 3.0-3.2, 4.0 47 | * Flask: 1.0-1.2, 2.0 48 | * Python 依赖包 49 | * psutil: >= 5.8.0 50 | * requests: >= 2.25.1 51 | * pip: >= 19.2.3 52 | 53 | ## 快速上手 54 | 55 | ### 快速使用 56 | 57 | 请参考:[快速开始](https://doc.dongtai.io/02_start/index.html) 58 | 59 | ### 快速开发 60 | 61 | 1. Fork [DongTai-agent-python](https://github.com/HXSecurity/DongTai-agent-python) 项目到自己的 github 仓库并 clone 项目: 62 | ```shell 63 | git clone https://github.com//DongTai-agent-python 64 | ``` 65 | 2. 根据需求编写代码 66 | 3. 修改配置文件 `dongtai_agent_python/config.json` 67 | * iast.server.token: "3d6bb430bc3e0b20dcc2d00000000000000a" 68 | * iast.server.url: "https://iast-test.huoxian.cn/openapi" 69 | * project.name: "DemoProjectName" 70 | > url 与 token 从洞态 IAST-web 页面(eg: https://iast-test.huoxian.cn/deploy) > python-agent 部署页面,下载 agent 的 shell 命令中获取,分别替换 url 域名与 token 71 | 4. 项目打包,在agent项目根目录执行 72 | ```shell 73 | python3 setup.py sdist 74 | ``` 75 | 5. 安装探针 \ 76 | 打包后会生成 dist 目录,在 dist 目录下找到安装包,将 dongtai_agent_python.tar.gz 安装包放入 Web 服务器所在机器上,执行 pip 安装 77 | ```shell 78 | pip3 install ./dongtai-python-agent.tar.gz 79 | ``` 80 | 81 | ## 项目接入探针 82 | 83 | ### 探针配置 84 | 85 | #### 环境变量 86 | 87 | * 开启调试: `DEBUG=1` 88 | * 自动创建项目: `AUTO_CREATE_PROJECT=1` 89 | * 项目名称: `PROJECT_NAME=Demo` 90 | * 项目版本: `PROJECT_VERSION=v1.0` 91 | * Agent 名称: `ENGINE_NAME=test-flask` 92 | * 日志文件路径: `LOG_PATH=/tmp/dongtai-agent-python.log` 93 | 94 | 也可以配置 `dongtai_agent_python/config.json` 中相关的配置项,同样生效 95 | 96 | * `debug` 97 | * `project.name` 98 | * `project.version` 99 | * `engine.name` 100 | * `log.log_path` 101 | 102 | > **注意: 环境变量的配置优先级高于配置文件** 103 | 104 | ### Django 105 | 106 | 1. 进入app的主目录 107 | 2. 打开 `app/settings.py` 文件,找到 `MIDDLEWARE` 所在行 108 | 3. 在该行的下面插入 `dongtai_agent_python.middlewares.django_middleware.FireMiddleware` 109 | 4. 重启 app 110 | 111 | ### Flask 112 | 113 | 1. 修改项目的入口文件(如 app.py), 增加如下内容 114 | ```python 115 | app = Flask(__name__) 116 | 117 | from dongtai_agent_python.middlewares.flask_middleware import AgentMiddleware 118 | app.wsgi_app = AgentMiddleware(app.wsgi_app, app) 119 | 120 | if __name__ == '__main__': 121 | app.run() 122 | ``` 123 | 2. 重启app 124 | -------------------------------------------------------------------------------- /dongtai_agent_python/__init__.py: -------------------------------------------------------------------------------- 1 | from dongtai_agent_python.context import ContextTracker 2 | 3 | 4 | CONTEXT_TRACKER = ContextTracker() 5 | -------------------------------------------------------------------------------- /dongtai_agent_python/api/__init__.py: -------------------------------------------------------------------------------- 1 | from .openapi import OpenAPI 2 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/assess/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/assess/c_api_hook.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from dongtai_agent_python.policy.deal_data import wrap_data 4 | from dongtai_agent_python.utils import scope 5 | 6 | module = sys.modules[__name__] 7 | 8 | CALLBACK_NAMES = { 9 | 'builtins.bytes.__new__': 'callback_bytes_cast', 10 | 'builtins.bytearray.__init__': 'callback_bytearray_cast', 11 | 'builtins.str.__new__': 'callback_unicode_cast', 12 | 'builtins.bytes.__add__': 'callback_bytes_concat', 13 | 'builtins.bytearray.__add__': 'callback_bytearray_concat', 14 | 'builtins.str.__add__': 'callback_unicode_concat', 15 | } 16 | 17 | 18 | def callback_propagator(policy_rule): 19 | def propagate(target, self_obj, result, args, kwargs): 20 | if scope.in_scope(scope.SCOPE_AGENT): 21 | return 22 | wrap_data(policy_rule, self_obj=self_obj, result=result, come_args=args, come_kwargs=kwargs) 23 | 24 | return propagate 25 | 26 | 27 | @scope.with_scope(scope.SCOPE_AGENT) 28 | def build_callback_function(policy_rule): 29 | if policy_rule.signature in CALLBACK_NAMES: 30 | callback_name = CALLBACK_NAMES[policy_rule.signature] 31 | else: 32 | callback_class_name = policy_rule.class_name 33 | if callback_class_name == 'str': 34 | callback_class_name = 'unicode' 35 | callback_name = "callback_{}_{}".format(callback_class_name, policy_rule.method_name) 36 | callback = callback_propagator(policy_rule) 37 | callback.__name__ = callback_name 38 | setattr(module, callback_name, callback) 39 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess/common_hook.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | from dongtai_agent_python.policy.deal_data import wrap_data 4 | from dongtai_agent_python.setting import const 5 | from dongtai_agent_python.utils import scope 6 | 7 | 8 | # 普通方法 hook 9 | class BuildFuncPatch(object): 10 | def __init__(self, origin_method, policy_rule): 11 | self.policy_rule = policy_rule 12 | self.policy_rule.set_origin_method(origin_method) 13 | self.policy_rule.set_patched_method(self) 14 | 15 | self.__name__ = origin_method.__name__ 16 | 17 | def __call__(self, *args, **kwargs): 18 | # edit by song to add speed 19 | with scope.scope(scope.SCOPE_AGENT): 20 | result = self.policy_rule.origin_method(*args, **kwargs) 21 | if scope.in_scope(scope.SCOPE_AGENT): 22 | return result 23 | 24 | wrap_data(self.policy_rule, result=result, come_args=args, come_kwargs=kwargs) 25 | 26 | return result 27 | 28 | 29 | def build_exec_eval_patch(origin_method, policy_rule): 30 | policy_rule.set_origin_method(origin_method) 31 | 32 | def exec_eval_patch(code, globs=None, locs=None): 33 | """ 34 | Code ported from six module 35 | @see: https://github.com/benjaminp/six/blob/45f1a230f9cc8e48372e19627b91ac06a2013292/six.py#L725 36 | """ 37 | 38 | if globs is None: 39 | frame = sys._getframe(1) 40 | 41 | globs = frame.f_globals 42 | if locs is None: 43 | locs = frame.f_locals 44 | del frame 45 | elif locs is None: 46 | locs = globs 47 | 48 | try: 49 | with scope.scope(scope.SCOPE_AGENT): 50 | result = origin_method(code, globs, locs) 51 | except Exception: 52 | raise 53 | 54 | if scope.in_scope(scope.SCOPE_AGENT): 55 | return result 56 | 57 | wrap_data(policy_rule, result=result, come_args=[code]) 58 | 59 | return result 60 | 61 | policy_rule.set_patched_method(exec_eval_patch) 62 | 63 | return exec_eval_patch 64 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess/ctypes_hook.py: -------------------------------------------------------------------------------- 1 | import ctypes 2 | import os 3 | import sys 4 | 5 | from dongtai_agent_python.policy.deal_data import wrap_data 6 | from dongtai_agent_python.setting import const 7 | from dongtai_agent_python.utils import scope 8 | 9 | 10 | # https://stackoverflow.com/a/24498525 11 | def magic_get_dict(o): 12 | # find address of dict whose offset is stored in the type 13 | dict_addr = id(o) + type(o).__dictoffset__ 14 | # retrieve the dict object itself 15 | dict_ptr = ctypes.cast(dict_addr, ctypes.POINTER(ctypes.py_object)) 16 | return dict_ptr.contents.value 17 | 18 | 19 | def magic_flush_mro_cache(): 20 | if os.name == "nt": 21 | pythonapi = ctypes.PyDLL("python dll", None, sys.dllhandle) 22 | elif sys.platform == "cygwin": 23 | pythonapi = ctypes.PyDLL("libpython%d.%d.dll" % sys.version_info[:2]) 24 | else: 25 | pythonapi = ctypes.PyDLL(None) 26 | 27 | pythonapi.PyType_Modified(ctypes.py_object(object)) 28 | 29 | 30 | # 属性方法hook 31 | def build_method_patch(origin_cls, policy_rule, *args, **kwargs): 32 | copy_new_class = type(origin_cls.__name__, origin_cls.__bases__, dict(origin_cls.__dict__)) 33 | if policy_rule.method_name not in copy_new_class.__dict__: 34 | return None 35 | origin_method = getattr(origin_cls, policy_rule.method_name) 36 | policy_rule.set_origin_method(origin_method) 37 | 38 | def child_func(*args, **kwargs): 39 | if policy_rule.node_type == const.NODE_TYPE_FILTER: 40 | with scope.scope(scope.SCOPE_AGENT): 41 | result = copy_new_class.__dict__[policy_rule.method_name](*args, **kwargs) 42 | else: 43 | result = copy_new_class.__dict__[policy_rule.method_name](*args, **kwargs) 44 | if scope.in_scope(scope.SCOPE_AGENT): 45 | return result 46 | 47 | wrap_data(policy_rule, result=result, come_args=args, come_kwargs=kwargs) 48 | 49 | return result 50 | 51 | policy_rule.set_patched_method(child_func) 52 | 53 | return child_func 54 | 55 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/.gitignore: -------------------------------------------------------------------------------- 1 | funchook/build -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/c_api.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | 6 | static PyMethodDef methods[] = { 7 | { 8 | "initialize", 9 | (PyCFunction)initialize, 10 | METH_VARARGS, 11 | "Initialize C API patcher" 12 | }, 13 | { 14 | "enable_patches", 15 | enable_patches, 16 | METH_O, 17 | "Patch relevant non-method functions" 18 | }, 19 | {"install", install, METH_O, "Install patches"}, 20 | {"str_origin", (PyCFunction)str_origin, METH_VARARGS, "Origin str cast method"}, 21 | {NULL, NULL, 0, NULL}, 22 | }; 23 | 24 | static struct PyModuleDef c_api_module = { 25 | PyModuleDef_HEAD_INIT, 26 | "c_api", 27 | "C API patch", 28 | -1, 29 | methods, 30 | NULL, 31 | NULL, 32 | NULL, 33 | NULL, 34 | }; 35 | 36 | PyMODINIT_FUNC PyInit_c_api(void) { 37 | PyObject *module; 38 | 39 | Py_Initialize(); 40 | module = PyModule_Create(&c_api_module); 41 | 42 | return module; 43 | } 44 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.ci/Dockerfile-alpine-test: -------------------------------------------------------------------------------- 1 | FROM alpine 2 | RUN apk add musl-dev gcc g++ make cmake git 3 | COPY . /funchook 4 | ENTRYPOINT ["/funchook/.ci/run-cmake-test.sh", "alpine"] 5 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.ci/run-cmake-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | set -e 3 | 4 | cd `dirname $0` 5 | cd .. 6 | 7 | dir=$1 8 | shift 9 | 10 | if expr "$dir" : ".*windows$" > /dev/null; then 11 | GENERATOR_TYPE=multi_config 12 | else 13 | GENERATOR_TYPE=single_config 14 | fi 15 | 16 | if test "`uname -m`" = aarch64; then 17 | DISASM_BACKENDS="capstone" 18 | else 19 | DISASM_BACKENDS="distorm zydis capstone" 20 | fi 21 | 22 | message() { 23 | echo "################# $* #################" 24 | } 25 | 26 | echodo() { 27 | echo '$' "$@" 28 | "$@" 29 | } 30 | 31 | build_and_test() { 32 | NAME=$1 33 | if test "$2"; then 34 | CONFIG_OPT="--config $2" 35 | BUILD_CONFIG_OPT="--build-config $2" 36 | else 37 | CONFIG_OPT="" 38 | BUILD_CONFIG_OPT="" 39 | fi 40 | message "build $NAME" 41 | echodo cmake --build . $CONFIG_OPT 42 | message "test $NAME" 43 | if ! echodo ctest --output-on-failure $BUILD_CONFIG_OPT; then 44 | cat test/debug.log 45 | exit 1 46 | fi 47 | } 48 | 49 | for disasm in $DISASM_BACKENDS; do 50 | case "$GENERATOR_TYPE" in 51 | multi_config) 52 | mkdir test-$dir-$disasm 53 | cd test-$dir-$disasm 54 | message "cmake (using $disasm as disassembler)" 55 | echodo cmake "$@" -DFUNCHOOK_DISASM=$disasm .. 56 | build_and_test Release Release 57 | build_and_test Debug Debug 58 | cd .. 59 | ;; 60 | single_config) 61 | mkdir test-$dir-$disasm-release 62 | cd test-$dir-$disasm-release 63 | message "cmake Release (using $disasm as disassembler)" 64 | echodo cmake -DCMAKE_BUILD_TYPE=Release "$@" -DFUNCHOOK_DISASM=$disasm .. 65 | build_and_test Release 66 | cd .. 67 | mkdir test-$dir-$disasm-debug 68 | cd test-$dir-$disasm-debug 69 | message "cmake Debug (using $disasm as disassembler)" 70 | echodo cmake -DCMAKE_BUILD_TYPE=Debug "$@" -DFUNCHOOK_DISASM=$disasm .. 71 | build_and_test Debug 72 | cd .. 73 | ;; 74 | esac 75 | done 76 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.dockerignore: -------------------------------------------------------------------------------- 1 | .git 2 | test-* 3 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.github/workflows/upload-assets-on-pushing-tag.yml: -------------------------------------------------------------------------------- 1 | on: 2 | push: 3 | tags: 4 | - 'v*' 5 | 6 | name: Upload Assets 7 | jobs: 8 | build: 9 | name: Upload Assets 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: Checkout code 13 | uses: actions/checkout@v2 14 | - name: Make Assets 15 | id: assets 16 | run: | 17 | DIR_NAME=funchook-$(gawk -F '[ ()]' '/set\(PROJECT_VERSION / {print $3}' CMakeLists.txt) 18 | TGZ_FILE_NAME=$DIR_NAME.tar.gz 19 | ZIP_FILE_NAME=$DIR_NAME.zip 20 | git clone --recursive . $DIR_NAME 21 | rm -rf $DIR_NAME/.dockerignore 22 | rm -rf $DIR_NAME/.git* 23 | rm -rf $DIR_NAME/.travis* 24 | rm -rf $DIR_NAME/distorm/.git 25 | rm -rf $DIR_NAME/distorm/MANIFEST* 26 | rm -rf $DIR_NAME/distorm/disOps 27 | rm -rf $DIR_NAME/distorm/examples 28 | rm -rf $DIR_NAME/distorm/make 29 | rm -rf $DIR_NAME/distorm/python 30 | rm -rf $DIR_NAME/distorm/setup* 31 | tar cfz $TGZ_FILE_NAME $DIR_NAME 32 | zip -rq $ZIP_FILE_NAME $DIR_NAME 33 | echo "::set-output name=tgz_file_name::$TGZ_FILE_NAME" 34 | echo "::set-output name=zip_file_name::$ZIP_FILE_NAME" 35 | - name: Create Release 36 | id: create_release 37 | uses: actions/create-release@v1 38 | env: 39 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 40 | with: 41 | tag_name: ${{ github.ref }} 42 | release_name: Release ${{ github.ref }} 43 | draft: false 44 | prerelease: false 45 | - name: Upload tar.gz asset 46 | uses: actions/upload-release-asset@v1 47 | env: 48 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 49 | with: 50 | upload_url: ${{ steps.create_release.outputs.upload_url }} 51 | asset_path: ./${{ steps.assets.outputs.tgz_file_name }} 52 | asset_name: ${{ steps.assets.outputs.tgz_file_name }} 53 | asset_content_type: application/gzip 54 | - name: Upload zip asset 55 | uses: actions/upload-release-asset@v1 56 | env: 57 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 58 | with: 59 | upload_url: ${{ steps.create_release.outputs.upload_url }} 60 | asset_path: ./${{ steps.assets.outputs.zip_file_name }} 61 | asset_name: ${{ steps.assets.outputs.zip_file_name }} 62 | asset_content_type: application/zip 63 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.gitignore: -------------------------------------------------------------------------------- 1 | *.dll 2 | *.lib 3 | *.o 4 | *.so 5 | *~ 6 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "distorm"] 2 | path = distorm 3 | url = https://github.com/gdabah/distorm.git 4 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/cmake/aarch64-linux-gnu.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_SYSTEM_NAME Linux) 2 | set(CMAKE_SYSTEM_PROCESSOR aarch64) 3 | set(TOOLCHAIN_PREFIX aarch64-linux-gnu) 4 | 5 | # cross compilers to use for C and C++ 6 | set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) 7 | set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) 8 | 9 | # target environment on the build host system 10 | set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) 11 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/cmake/capstone.cmake.in: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.6) 2 | 3 | include(ExternalProject) 4 | 5 | project(capstone-download NONE) 6 | 7 | ExternalProject_Add(external_capstone 8 | GIT_REPOSITORY https://github.com/aquynh/capstone.git 9 | GIT_TAG 4.0.2 10 | GIT_SHALLOW TRUE 11 | SOURCE_DIR "${CMAKE_CURRENT_BINARY_DIR}/capstone-src" 12 | BINARY_DIR "${CMAKE_CURRENT_BINARY_DIR}/capstone-build" 13 | CONFIGURE_COMMAND "" 14 | BUILD_COMMAND "" 15 | INSTALL_COMMAND "" 16 | TEST_COMMAND "" 17 | ) 18 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/cmake/i686-w64-mingw32.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_SYSTEM_NAME Windows) 2 | set(CMAKE_SYSTEM_PROCESSOR i686) 3 | set(TOOLCHAIN_PREFIX i686-w64-mingw32) 4 | 5 | # cross compilers to use for C and C++ 6 | set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) 7 | set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) 8 | 9 | # target environment on the build host system 10 | set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) 11 | 12 | set(CMAKE_C_FLAGS "-D_WIN32_WINNT=0x600 -m32 -static-libgcc" CACHE STRING "" FORCE) 13 | set(CMAKE_ASM_FLAGS "-m32" CACHE STRING "" FORCE) 14 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/cmake/x86_64-w64-mingw32.cmake: -------------------------------------------------------------------------------- 1 | set(CMAKE_SYSTEM_NAME Windows) 2 | set(CMAKE_SYSTEM_PROCESSOR x86_64) 3 | set(TOOLCHAIN_PREFIX x86_64-w64-mingw32) 4 | 5 | # cross compilers to use for C and C++ 6 | set(CMAKE_C_COMPILER ${TOOLCHAIN_PREFIX}-gcc) 7 | set(CMAKE_CXX_COMPILER ${TOOLCHAIN_PREFIX}-g++) 8 | 9 | # target environment on the build host system 10 | set(CMAKE_FIND_ROOT_PATH /usr/${TOOLCHAIN_PREFIX}) 11 | 12 | set(CMAKE_C_FLAGS -D_WIN32_WINNT=0x600 CACHE STRING "" FORCE) 13 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/.github/workflows/py.yml: -------------------------------------------------------------------------------- 1 | name: Python package 2 | 3 | on: [push] 4 | 5 | jobs: 6 | build: 7 | runs-on: ${{ matrix.os }} 8 | strategy: 9 | max-parallel: 4 10 | matrix: 11 | os: [ubuntu-18.04, windows-latest, macos-latest] 12 | python-version: [2.7, 3.5] 13 | exclude: 14 | # This combination requires MSVC 9, which is difficult here 15 | - os: windows-latest 16 | python-version: 2.7 17 | steps: 18 | - uses: actions/checkout@v1 19 | - name: Set up Python ${{ matrix.python-version }} 20 | uses: actions/setup-python@v1 21 | with: 22 | python-version: ${{ matrix.python-version }} 23 | - uses: ilammy/msvc-dev-cmd@v1 24 | - name: Build and install package 25 | run: | 26 | python -m pip install --upgrade pip setuptools wheel 27 | python setup.py bdist_wheel 28 | pip install --find-links=dist --no-index distorm3 29 | - uses: actions/upload-artifact@v1 30 | with: 31 | name: Wheels 32 | path: dist 33 | - name: Test importing 34 | run: python -c 'import distorm3' 35 | - name: Install yasm (macOS) 36 | run: brew install yasm 37 | if: runner.os == 'macOS' 38 | - name: Install yasm (Ubuntu) 39 | run: sudo apt-get install -y yasm 40 | if: runner.os == 'Linux' 41 | - name: Copy yasm (Windows) 42 | run: copy test-deps\yasm-1.3.0-win64.exe python\yasm.exe 43 | if: runner.os == 'Windows' 44 | - name: Run test_distorm3.py 45 | working-directory: ./python 46 | run: python test_distorm3.py 47 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/.gitignore: -------------------------------------------------------------------------------- 1 | *.egg-info 2 | *.py[cod] 3 | *.so 4 | build 5 | dist 6 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/COPYING: -------------------------------------------------------------------------------- 1 | :[diStorm3}: 2 | The ultimate disassembler library. 3 | Copyright (c) 2003-2021, Gil Dabah 4 | All rights reserved. 5 | 6 | Redistribution and use in source and binary forms, with or without 7 | modification, are permitted provided that the following conditions are met: 8 | * Redistributions of source code must retain the above copyright 9 | notice, this list of conditions and the following disclaimer. 10 | * Redistributions in binary form must reproduce the above copyright 11 | notice, this list of conditions and the following disclaimer in the 12 | documentation and/or other materials provided with the distribution. 13 | * Neither the name of the Gil Dabah nor the 14 | names of its contributors may be used to endorse or promote products 15 | derived from this software without specific prior written permission. 16 | 17 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 18 | ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 19 | WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 20 | DISCLAIMED. IN NO EVENT SHALL GIL DABAH BE LIABLE FOR ANY 21 | DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 22 | (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 23 | LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 24 | ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 25 | (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 26 | SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 27 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/MANIFEST.in: -------------------------------------------------------------------------------- 1 | include COPYING setup.cfg setup.py 2 | include make\win32\cdistorm.vcxproj make\win32\cdistorm.vcxproj.filters make\win32\distorm.sln make\win32\resource.h make\win32\Resource.rc 3 | recursive-include src *.c *.h 4 | recursive-include include *.h 5 | recursive-include python *.py 6 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/README.md: -------------------------------------------------------------------------------- 1 | Powerful Disassembler Library For x86/AMD64 2 | ----------- 3 | 4 | Welcome to the diStorm3 binary stream disassembler library project. 5 | 6 | diStorm3 is really a decomposer, which means it takes an instruction and returns a binary structure which describes it rather than static text, which is great for advanced binary code analysis. 7 | 8 | diStorm3 is super lightweight (~45KB), ultra fast and easy to use (a single API)! 9 | 10 | For a tested and light hooking library see the https://github.com/gdabah/distormx project. 11 | 12 | "We benchmarked five popular open-source disassembly libraries and chose diStorm3, which had the best performance (and furthermore, has complete 64-bit support).", July 2014, Quoting David Williams-King in his Thesis about Binary Shuffling. 13 | 14 | diStorm3 is licensed under BSD! 15 | 16 | Installing diStorm3 - 17 | Clone repo locally and then 'python setup.py install' or alternatively: 'python -m pip install distorm3'. 18 | 19 | For Windows, use these pre-built installers in https://pypi.org/project/distorm3/#files. 20 | 21 | RTFM, the wiki has plenty of info. 22 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/disOps/registers.py: -------------------------------------------------------------------------------- 1 | # All VIAL and diStorm3 code are based on the order of this list, do NOT edit! 2 | REGISTERS = [ 3 | "RAX", "RCX", "RDX", "RBX", "RSP", "RBP", "RSI", "RDI", "R8", "R9", "R10", "R11", "R12", "R13", "R14", "R15", "XX", 4 | "EAX", "ECX", "EDX", "EBX", "ESP", "EBP", "ESI", "EDI", "R8D", "R9D", "R10D", "R11D", "R12D", "R13D", "R14D", "R15D", "XX", 5 | "AX", "CX", "DX", "BX", "SP", "BP", "SI", "DI", "R8W", "R9W", "R10W", "R11W", "R12W", "R13W", "R14W", "R15W", "XX", 6 | "AL", "CL", "DL", "BL", "AH", "CH", "DH", "BH", "R8B", "R9B", "R10B", "R11B", "R12B", "R13B", "R14B", "R15B", "XX", 7 | "SPL", "BPL", "SIL", "DIL", "XX", 8 | "ES", "CS", "SS", "DS", "FS", "GS", "XX", 9 | "RIP", "XX", 10 | "ST0", "ST1", "ST2", "ST3", "ST4", "ST5", "ST6", "ST7", "XX", 11 | "MM0", "MM1", "MM2", "MM3", "MM4", "MM5", "MM6", "MM7", "XX", 12 | "XMM0", "XMM1", "XMM2", "XMM3", "XMM4", "XMM5", "XMM6", "XMM7", "XMM8", "XMM9", "XMM10", "XMM11", "XMM12", "XMM13", "XMM14", "XMM15", "XX", 13 | "YMM0", "YMM1", "YMM2", "YMM3", "YMM4", "YMM5", "YMM6", "YMM7", "YMM8", "YMM9", "YMM10", "YMM11", "YMM12", "YMM13", "YMM14", "YMM15", "XX", 14 | "CR0", "", "CR2", "CR3", "CR4", "", "", "", "CR8", "XX", 15 | "DR0", "DR1", "DR2", "DR3", "", "", "DR6", "DR7"] 16 | 17 | regsText = "const _WRegister _REGISTERS[] = {\n\t" 18 | regsEnum = "typedef enum {\n\t" 19 | old = "*" 20 | unused = 0 21 | for i in REGISTERS: 22 | if old != "*": 23 | if old == "XX": 24 | regsText += "\n\t" 25 | regsEnum += "\n\t" 26 | old = i 27 | continue 28 | else: 29 | regsText += "{%d, \"%s\"}," % (len(old), old) 30 | if len(old): 31 | regsEnum += "R_%s," % old 32 | else: 33 | regsEnum += "R_UNUSED%d," % unused 34 | unused += 1 35 | if i != "XX": 36 | regsText += " " 37 | regsEnum += " " 38 | old = i 39 | regsText += "{%d, \"%s\"},\n\t{0, \"\"} /* There must be an empty last reg, see strcat_WSR. */\n};\n" % (len(old), old) 40 | regsEnum += "R_" + old + "\n} _RegisterType;\n" 41 | 42 | print(regsEnum) 43 | print(regsText) 44 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/TestdiStorm/Program.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Reflection; 3 | using System.Reflection.Emit; 4 | using diStorm; 5 | 6 | namespace TestdiStorm 7 | { 8 | public class Program 9 | { 10 | private static IntPtr LeakNativeMethodPtr(MethodInfo x) 11 | { 12 | 13 | //if ((x.MethodImplementationFlags & MethodImplAttributes.InternalCall) != 0) 14 | // Console.WriteLine("{0} is an InternalCall method. These methods always point to the same address.", x.Name); 15 | var domain = AppDomain.CurrentDomain; 16 | var dynAsm = new AssemblyName("MethodLeakAssembly"); 17 | var asmBuilder = domain.DefineDynamicAssembly(dynAsm, AssemblyBuilderAccess.Run); 18 | var moduleBuilder = asmBuilder.DefineDynamicModule("MethodLeakModule"); 19 | var typeBuilder = moduleBuilder.DefineType("MethodLeaker", TypeAttributes.Public); 20 | var p = new Type[0]; 21 | var methodBuilder = typeBuilder.DefineMethod("LeakNativeMethodPtr", MethodAttributes.Public | MethodAttributes.Static, typeof(IntPtr), null); 22 | var generator = methodBuilder.GetILGenerator(); 23 | 24 | // Push unmanaged pointer to MethodInfo onto the evaluation stack 25 | generator.Emit(OpCodes.Ldftn, x); 26 | // Convert the pointer to type - unsigned int64 27 | //generator.Emit(OpCodes.Conv_Ovf_U); 28 | generator.Emit(OpCodes.Ret); 29 | 30 | // Assemble everything 31 | var type = typeBuilder.CreateType(); 32 | 33 | var method = type.GetMethod("LeakNativeMethodPtr"); 34 | 35 | try { 36 | // Call the method and return its JITed address 37 | var address = (IntPtr) method.Invoke(null, new object[0]); 38 | 39 | Console.WriteLine("0x{0}", address.ToString(string.Format("X{0})", IntPtr.Size * 2))); 40 | return address; 41 | } 42 | catch (Exception e) { 43 | Console.WriteLine("{0} cannot return an unmanaged address."); 44 | } 45 | return IntPtr.Zero; 46 | } 47 | 48 | 49 | private static unsafe void Main(string[] args) 50 | { 51 | var buf = new byte[4]; 52 | buf[0] = (byte) 0xc3; 53 | buf[1] = (byte) 0x33; 54 | buf[2] = (byte) 0xc0; 55 | buf[3] = (byte) 0xc3; 56 | var ci = new CodeInfo((long) 0x1000, buf, DecodeType.Decode32Bits, 0); 57 | var dr = new DecodedResult(10); 58 | diStorm3.Decode(ci, dr); 59 | 60 | foreach (var x in dr.Instructions) { 61 | var s = String.Format("{0:X} {1} {2}", x.Offset, x.Mnemonic, x.Operands); 62 | Console.WriteLine(s); 63 | } 64 | 65 | var dr2 = new DecomposedResult(10); 66 | diStorm3.Decompose(ci, dr2); 67 | 68 | foreach (var y in dr2.Instructions) { 69 | if (y.Opcode != Opcode.RET) 70 | { 71 | var x = diStorm3.Format(ci, y); 72 | var s = String.Format("{0:X} {1} {2}", x.Offset, x.Mnemonic, x.Operands); 73 | Console.WriteLine(s); 74 | } 75 | } 76 | 77 | } 78 | } 79 | } 80 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/TestdiStorm/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("TestDiStorm")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("TestDiStorm")] 13 | [assembly: AssemblyCopyright("Copyright © 2012")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("737cf66b-c136-47be-b92d-3f2fefbaf27a")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/TestdiStorm/TestdiStorm.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC} 8 | Exe 9 | Properties 10 | TestDiStorm 11 | TestDiStorm 12 | v4.0 13 | 512 14 | 15 | 16 | 17 | x64 18 | true 19 | full 20 | false 21 | bin\Debug\ 22 | DEBUG;TRACE 23 | prompt 24 | 4 25 | true 26 | false 27 | 28 | 29 | x64 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | true 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | {137ade63-2489-4235-91c6-6cb664cab63f} 55 | distorm-net 56 | 57 | 58 | 59 | 60 | copy $(SolutionDir)\..\..\distorm3.dll $(TargetDir) 61 | 62 | 69 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2012 4 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "distorm-net", "distorm-net\distorm-net.csproj", "{137ADE63-2489-4235-91C6-6CB664CAB63F}" 5 | EndProject 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestdiStorm", "TestDiStorm\TestdiStorm.csproj", "{2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {137ADE63-2489-4235-91C6-6CB664CAB63F}.Release|Any CPU.Build.0 = Release|Any CPU 18 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 19 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Debug|Any CPU.Build.0 = Debug|Any CPU 20 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Release|Any CPU.ActiveCfg = Release|Any CPU 21 | {2F2F3CBD-F968-47E4-ADEC-D42E42A924AC}.Release|Any CPU.Build.0 = Release|Any CPU 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | EndGlobal 27 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/CodeInfo.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace diStorm 4 | { 5 | public class CodeInfo 6 | { 7 | public CodeInfo(long codeOffset, byte[] rawCode, DecodeType dt, int features) 8 | { 9 | _code = new byte[rawCode.Length]; 10 | Array.Copy(rawCode, _code, _code.Length); 11 | 12 | _codeOffset = codeOffset; 13 | _decodeType = dt; 14 | _features = features; 15 | } 16 | 17 | internal long _codeOffset; 18 | internal long _nextOffset; 19 | internal byte[] _code; 20 | internal DecodeType _decodeType; 21 | internal int _features; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/DecodedInst.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace diStorm 4 | { 5 | public class DecodedInst 6 | { 7 | internal DecodedInst() { } 8 | 9 | public string Mnemonic { get; internal set; } 10 | public string Operands { get; internal set; } 11 | public string Hex { get; internal set; } 12 | public uint Size { get; internal set; } 13 | public IntPtr Offset { get; internal set; } 14 | } 15 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/DecodedResult.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace diStorm 3 | { 4 | public class DecodedResult 5 | { 6 | public DecodedResult(int maxInstructions) 7 | { 8 | MaxInstructions = maxInstructions; 9 | Instructions = null; 10 | } 11 | public DecodedInst[] Instructions { get; internal set; } 12 | public int MaxInstructions { get; internal set; } 13 | } 14 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/DecomposedInst.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | 3 | namespace diStorm 4 | { 5 | public class DecomposedInst 6 | { 7 | public class ImmVariant 8 | { 9 | public ulong Imm { get; internal set; } 10 | public int Size { get; internal set; } 11 | } 12 | public class DispVariant 13 | { 14 | public ulong Displacement { get; internal set; } 15 | public int Size { get; internal set; } 16 | } 17 | internal int _segment; 18 | public IntPtr Address { get; internal set; } 19 | public ushort Flags { get; internal set; } 20 | public int Size { get; internal set; } 21 | public Opcode Opcode { get; internal set; } 22 | public int Segment { get { return _segment & 0x7f; } } 23 | public bool IsSegmentDefault { get { return (_segment & 0x80) == 0x80; } } 24 | public int Base { get; internal set; } 25 | public int Scale { get; internal set; } 26 | public int UnusedPrefixesMask { get; internal set; } 27 | public int Meta { get; internal set; } 28 | public int RegistersMask { get; internal set; } 29 | public int ModifiedFlagsMask { get; internal set; } 30 | public int TestedFlagsMask { get; internal set; } 31 | public int UndefinedFlagsMask { get; internal set; } 32 | public ImmVariant Imm { get; internal set; } 33 | public DispVariant Disp { get; internal set; } 34 | public Operand[] Operands { get; internal set; } 35 | } 36 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/DecomposedResult.cs: -------------------------------------------------------------------------------- 1 | namespace diStorm 2 | { 3 | public class DecomposedResult 4 | { 5 | public DecomposedResult(int maxInstructions) 6 | { 7 | MaxInstructions = maxInstructions; 8 | Instructions = null; 9 | } 10 | 11 | public DecomposedInst[] Instructions { get; internal set; } 12 | public int MaxInstructions { get; private set; } 13 | } 14 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/Opcodes.tt: -------------------------------------------------------------------------------- 1 | <#@ template debug="true" hostSpecific="true" #> 2 | <#@ output extension=".cs" #> 3 | <#@ Assembly Name="System.Core" #> 4 | <#@ Assembly Name="System.Windows.Forms" #> 5 | <#@ import namespace="System" #> 6 | <#@ import namespace="System.IO" #> 7 | <#@ import namespace="System.Diagnostics" #> 8 | <#@ import namespace="System.Linq" #> 9 | <#@ import namespace="System.Collections" #> 10 | <#@ import namespace="System.Collections.Generic" #> 11 | <#@ import namespace="System.Text.RegularExpressions" #> 12 | // This file was auto generated from the distrom opcodes.h file 13 | // on <#= DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.FFF") #> 14 | <# 15 | var mnemonics = File.ReadAllText(Host.ResolvePath(@"..\..\..\include\mnemonics.h")); 16 | var instRe = new Regex("typedef enum {(.+)} _InstructionType;", RegexOptions.Singleline); 17 | var regRe = new Regex("typedef enum {(.+)} _RegisterType;", RegexOptions.Singleline); 18 | var m = instRe.Match(mnemonics); 19 | var insts = m.Groups[1].Value.Split(',').Select(x => new { 20 | Name = x.Split('=')[0].Trim().Substring(2), 21 | Value = x.Split('=')[1].Trim(), 22 | }).ToArray(); 23 | m = regRe.Match(mnemonics, m.Index + m.Length); 24 | var regs = m.Groups[1].Value.Split(',').Select(x => x.Trim()).ToArray(); 25 | #> 26 | namespace diStorm 27 | { 28 | public enum Opcode : ushort { 29 | <# foreach (var i in insts) { #> 30 | <#= i.Name #> = <#= i.Value #>,<# } #> 31 | } 32 | 33 | public enum Register { 34 | <# foreach (var r in regs) { #> 35 | <#= r #>,<# } #> 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/Operand.cs: -------------------------------------------------------------------------------- 1 | 2 | namespace diStorm 3 | { 4 | 5 | public enum OperandType : byte 6 | { 7 | None, 8 | Reg, 9 | Imm, 10 | Imm1, 11 | Imm2, 12 | Disp, 13 | Smem, 14 | Mem, 15 | Pc, 16 | Ptr 17 | } 18 | 19 | public class Operand 20 | { 21 | public OperandType Type { get; internal set; } 22 | public int Index { get; internal set; } 23 | public int Size { get; internal set; } 24 | } 25 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("distorm-net")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("distorm-net")] 13 | [assembly: AssemblyCopyright("Copyright © 2012")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("ddf3403b-11ea-4470-9fb3-03e68ac68fb5")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/distorm-net/distorm-net.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {137ADE63-2489-4235-91C6-6CB664CAB63F} 8 | Library 9 | Properties 10 | diStorm 11 | diStorm 12 | v4.0 13 | 512 14 | 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | true 25 | x64 26 | 27 | 28 | pdbonly 29 | true 30 | bin\Release\ 31 | TRACE 32 | prompt 33 | 4 34 | true 35 | x64 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | True 51 | True 52 | Opcodes.tt 53 | 54 | 55 | 56 | 57 | 58 | TextTemplatingFileGenerator 59 | Opcodes.cs 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | 73 | 80 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/cs/readme: -------------------------------------------------------------------------------- 1 | This is a .NET Wrapper of the distorm project for seamless decompilation of 32-bit and 64-bit intel binaries. 2 | This project is licensed under the GPLv3. 3 | By Dan Shechter -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/README: -------------------------------------------------------------------------------- 1 | diStorm3 for Ring 0 2 | Gil Dabah Aug 2010 3 | http://ragestorm.net/distorm/ 4 | 5 | Tested sample with DDK 7600.16385.1 using WinXPSP2. 6 | 7 | Steps of how to build the diStorm64 sample using the DDK. 8 | 9 | Warning - Make sure the path you extracted diStorm to does not include any spaces, otherwise you will get an error from the build. 10 | 11 | 1) Open the DDK's build environment, for example: "Win XP Free Build Environment", 12 | which readies the evnrionment variables for building a driver. Or run the SETENV.BAT in console. 13 | 14 | 2) Launch "build", once you're in the directory of the /ddkproj. 15 | 16 | 3) If everything worked smoothly, you should see a new file named "distorm.sys" under objfre_wxp_x86\i386 17 | (that's if you use WinXP and the Free Environment). 18 | 19 | - If you experienced any errors, try moving the whole distorm directory to c:\winddk\src\ 20 | (or any other directory tree which doesn't contain spaces in its name). 21 | 22 | 4) Now you will have to register the new driver: 23 | a. Copy the distorm.sys file to \windows\system32\drivers\. 24 | b. Use the DDK's regini.exe with the supplied distorm.ini. 25 | c. Restart Windows for the effect to take place. :( 26 | 27 | **The alternative is to use some tool like KmdManager.exe, which will register the driver without a need for the .ini file, nor a reboot. 28 | 29 | 30 | 5) Now open your favorite debug-strings monitor (mine is DebugView). 31 | Make sure you monitor kernel debug-strings. 32 | 33 | 6) Launching "net start distorm" from command line, will run the DriverEntry code in "main.c", 34 | which will disassemble a few instructions from the KeBugcheck routine and dump it using DbgPrint. 35 | 36 | 37 | NOTES: 38 | -+---- 39 | The sample uses the stack for storing the results from the decode function. 40 | If you have too many structures on the stack, you better allocate memory before calling the decode function, 41 | and later on free that memory. Don't use the NONPAGED pool if you don't really need it. 42 | 43 | _OffsetType is the type of the DecodedInstruction.Offset field, which defaults to 64bits, 44 | so make sure that when you print this variable you use %I64X, or when you use it anywhere else, you use the _OffsetType as well. 45 | Notice that we call directly distorm_decode64, since we SUPPORT_64BIT_OFFSET and because we don't have the macros of distorm.h. 46 | 47 | diStorm can be really compiled for all IRQL, it doesn't use any resource or the standard C library at all. 48 | Although the sample uses diStorm at PASSIVE level. 49 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/distorm.ini: -------------------------------------------------------------------------------- 1 | \registry\machine\system\currentcontrolset\services\distorm 2 | ImagePath = system32\drivers\distorm.sys 3 | DisplayName = "distorm" 4 | Type = REG_DWORD 0x1 5 | Start = REG_DWORD 0x3 6 | Group = Extended base 7 | ErrorControl = REG_DWORD 0x1 8 | \registry\machine\system\currentcontrolset\services\distorm\Parameters 9 | BreakOnEntry = REG_DWORD 0x0 10 | DebugMask = REG_DWORD 0x0 11 | LogEvents = REG_DWORD 0x0 -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/dummy.c: -------------------------------------------------------------------------------- 1 | // Since the DDK's nmake is limited with directories, we will bypass that with this simple hack. 2 | // Thanks to Razvan Hobeanu. 3 | // Sep 2009. 4 | 5 | 6 | #include "../src/mnemonics.c" 7 | #include "../src/wstring.c" 8 | #include "../src/textdefs.c" 9 | #include "../src/x86defs.c" 10 | #include "../src/prefix.c" 11 | #include "../src/operands.c" 12 | #include "../src/insts.c" 13 | #include "../src/instructions.c" 14 | #include "../src/distorm.c" 15 | #include "../src/decoder.c" 16 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * main.c 3 | * Sample kernel driver to show how diStorm can be easily compiled and used in Ring 0. 4 | * 5 | * /// Follow the README file in order to compile diStorm using the DDK. \\\ 6 | * 7 | * Izik, Gil Dabah 8 | * Jan 2007 9 | * http://ragestorm.net/distorm/ 10 | */ 11 | 12 | #include 13 | #include "../include/distorm.h" 14 | #include "dummy.c" 15 | 16 | // The number of the array of instructions the decoder function will use to return the disassembled instructions. 17 | // Play with this value for performance... 18 | #define MAX_INSTRUCTIONS (15) 19 | 20 | void DriverUnload(IN PDRIVER_OBJECT DriverObject) 21 | { 22 | } 23 | 24 | NTSTATUS DriverEntry(IN PDRIVER_OBJECT DriverObject, IN PUNICODE_STRING RegistryPath) 25 | { 26 | UNICODE_STRING pFcnName; 27 | 28 | // Holds the result of the decoding. 29 | _DecodeResult res; 30 | // Decoded instruction information. 31 | _DecodedInst decodedInstructions[MAX_INSTRUCTIONS]; 32 | // next is used for instruction's offset synchronization. 33 | // decodedInstructionsCount holds the count of filled instructions' array by the decoder. 34 | unsigned int decodedInstructionsCount = 0, i, next; 35 | // Default decoding mode is 32 bits, could be set by command line. 36 | _DecodeType dt = Decode32Bits; 37 | 38 | // Default offset for buffer is 0, could be set in command line. 39 | _OffsetType offset = 0; 40 | char* errch = NULL; 41 | 42 | // Buffer to disassemble. 43 | unsigned char *buf; 44 | int len = 100; 45 | 46 | // Register unload routine 47 | DriverObject->DriverUnload = DriverUnload; 48 | 49 | DbgPrint("diStorm Loaded!\n"); 50 | 51 | // Get address of KeBugCheck 52 | RtlInitUnicodeString(&pFcnName, L"KeBugCheck"); 53 | buf = (char *)MmGetSystemRoutineAddress(&pFcnName); 54 | offset = (unsigned) (_OffsetType)buf; 55 | 56 | DbgPrint("Resolving KeBugCheck @ 0x%08x\n", buf); 57 | // Decode the buffer at given offset (virtual address). 58 | 59 | while (1) { 60 | res = distorm_decode64(offset, (const unsigned char*)buf, len, dt, decodedInstructions, MAX_INSTRUCTIONS, &decodedInstructionsCount); 61 | if (res == DECRES_INPUTERR) { 62 | DbgPrint(("NULL Buffer?!\n")); 63 | break; 64 | } 65 | 66 | for (i = 0; i < decodedInstructionsCount; i++) { 67 | // Note that we print the offset as a 64 bits variable!!! 68 | // It might be that you'll have to change it to %08X... 69 | DbgPrint("%08I64x (%02d) %s %s %s\n", decodedInstructions[i].offset, decodedInstructions[i].size, 70 | (char*)decodedInstructions[i].instructionHex.p, 71 | (char*)decodedInstructions[i].mnemonic.p, 72 | (char*)decodedInstructions[i].operands.p); 73 | } 74 | 75 | if (res == DECRES_SUCCESS || decodedInstructionsCount == 0) { 76 | break; // All instructions were decoded. 77 | } 78 | 79 | // Synchronize: 80 | next = (unsigned int)(decodedInstructions[decodedInstructionsCount-1].offset - offset); 81 | next += decodedInstructions[decodedInstructionsCount-1].size; 82 | 83 | // Advance ptr and recalc offset. 84 | buf += next; 85 | len -= next; 86 | offset += next; 87 | } 88 | 89 | DbgPrint(("Done!\n")); 90 | return STATUS_UNSUCCESSFUL; // Make sure the driver doesn't stay resident, so we can recompile and run again! 91 | } 92 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/makefile: -------------------------------------------------------------------------------- 1 | !INCLUDE $(NTMAKEENV)\makefile.def -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/ddk/sources: -------------------------------------------------------------------------------- 1 | TARGETNAME = distorm 2 | TARGETPATH = obj 3 | TARGETTYPE = DRIVER 4 | 5 | C_DEFINES = $(C_DEFINES) -DSUPPORT_64BIT_OFFSET -DLIBDISTORM 6 | 7 | INCLUDES = %BUILD%\inc;..\src; 8 | LIBS = %BUILD%\lib 9 | 10 | SOURCES = main.c 11 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/Makefile: -------------------------------------------------------------------------------- 1 | UNAME_S := $(shell uname -s) 2 | 3 | ifeq ($(UNAME_S),Darwin) 4 | 5 | JAVA_HOME=$(shell /usr/libexec/java_home) 6 | 7 | all: libjdistorm.dylib 8 | libjdistorm.dylib: jdistorm.c jdistorm.h 9 | gcc -dynamiclib -o libjdistorm.dylib jdistorm.c -I ${JAVA_HOME}/include/ -I ${JAVA_HOME}/include/darwin/ -ldistorm3 10 | 11 | endif 12 | 13 | ifeq ($(UNAME_S),Linux) 14 | 15 | all: libjdistorm.so 16 | jdistorm.o: jdistorm.c jdistorm.h 17 | gcc -c jdistorm.c -fPIC -I ${JAVA_HOME}/include -I ${JAVA_HOME}/include/linux 18 | 19 | libjdistorm.so: jdistorm.o 20 | gcc -shared -o libjdistorm.so -L${JAVA_HOME}/jre/lib -ldistorm3 jdistorm.o 21 | 22 | endif 23 | 24 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | distorm 4 | 5 | 6 | 7 | 8 | 9 | org.eclipse.jdt.core.javabuilder 10 | 11 | 12 | 13 | 14 | 15 | org.eclipse.jdt.core.javanature 16 | 17 | 18 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/.settings/org.eclipse.jdt.core.prefs: -------------------------------------------------------------------------------- 1 | #Sun Oct 31 17:27:29 IST 2010 2 | eclipse.preferences.version=1 3 | org.eclipse.jdt.core.compiler.codegen.inlineJsrBytecode=enabled 4 | org.eclipse.jdt.core.compiler.codegen.targetPlatform=1.6 5 | org.eclipse.jdt.core.compiler.codegen.unusedLocal=preserve 6 | org.eclipse.jdt.core.compiler.compliance=1.6 7 | org.eclipse.jdt.core.compiler.debug.lineNumber=generate 8 | org.eclipse.jdt.core.compiler.debug.localVariable=generate 9 | org.eclipse.jdt.core.compiler.debug.sourceFile=generate 10 | org.eclipse.jdt.core.compiler.problem.assertIdentifier=error 11 | org.eclipse.jdt.core.compiler.problem.enumIdentifier=error 12 | org.eclipse.jdt.core.compiler.source=1.6 13 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/Main.java: -------------------------------------------------------------------------------- 1 | import java.nio.ByteBuffer; 2 | 3 | import diStorm3.distorm3.*; 4 | import diStorm3.CodeInfo; 5 | import diStorm3.DecodedInst; 6 | import diStorm3.OpcodeEnum; 7 | import diStorm3.distorm3; 8 | import diStorm3.DecodedResult; 9 | import diStorm3.DecomposedResult; 10 | import diStorm3.DecomposedInst; 11 | 12 | public class Main { 13 | 14 | public static void main(String[] args) { 15 | byte[] buf = new byte[4]; 16 | buf[0] = (byte)0xc3; 17 | buf[1] = (byte)0x33; 18 | buf[2] = (byte)0xc0; 19 | buf[3] = (byte)0xc3; 20 | CodeInfo ci = new CodeInfo((long)0x1000, buf, DecodeType.Decode32Bits, 0); 21 | DecodedResult dr = new DecodedResult(10); 22 | distorm3.Decode(ci, dr); 23 | 24 | for (DecodedInst x : dr.mInstructions) { 25 | String s = String.format("%x %s %s", x.getOffset(), x.getMnemonic(), x.getOperands()); 26 | System.out.println(s); 27 | } 28 | 29 | DecomposedResult dr2 = new DecomposedResult(10); 30 | distorm3.Decompose(ci, dr2); 31 | 32 | for (DecomposedInst y: dr2.mInstructions) { 33 | if (y.getOpcode() != OpcodeEnum.RET) { 34 | DecodedInst x = distorm3.Format(ci, y); 35 | String s = String.format("%x %s %s", x.getOffset(), x.getMnemonic(), x.getOperands()); 36 | System.out.println(s); 37 | } 38 | } 39 | 40 | } 41 | 42 | 43 | } 44 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/CodeInfo.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | import java.nio.ByteBuffer; 4 | 5 | public class CodeInfo { 6 | public CodeInfo(long codeOffset, ByteBuffer code, distorm3.DecodeType dt, int features) { 7 | mCodeOffset = codeOffset; 8 | mCode = code; 9 | mDecodeType = dt.ordinal(); 10 | mFeatures = features; 11 | mAddrMask = 0; 12 | } 13 | 14 | public CodeInfo(long codeOffset, byte[] rawCode, distorm3.DecodeType dt, int features) { 15 | mCode = ByteBuffer.allocateDirect(rawCode.length); 16 | mCode.put(rawCode); 17 | 18 | mCodeOffset = codeOffset; 19 | mDecodeType = dt.ordinal(); 20 | mFeatures = features; 21 | mAddrMask = 0; 22 | } 23 | 24 | private long mAddrMask; 25 | private long mCodeOffset; 26 | private long mNextOffset; 27 | private ByteBuffer mCode; 28 | private int mDecodeType; 29 | private int mFeatures; 30 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/DecodedInst.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | public class DecodedInst { 4 | DecodedInst() 5 | { 6 | } 7 | private String mMnemonic; 8 | private String mOperands; 9 | private String mHex; 10 | private int mSize; 11 | private long mOffset; 12 | 13 | public String getMnemonic() { 14 | return mMnemonic; 15 | } 16 | 17 | public String getOperands() { 18 | return mOperands; 19 | } 20 | 21 | public String getHex() { 22 | return mHex; 23 | } 24 | 25 | public int getSize() { 26 | return mSize; 27 | } 28 | 29 | public long getOffset() { 30 | return mOffset; 31 | } 32 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/DecodedResult.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | public class DecodedResult { 4 | public DecodedResult(int maxInstructions) { 5 | mMaxInstructions = maxInstructions; 6 | mInstructions = null; 7 | } 8 | 9 | public DecodedInst[] mInstructions; 10 | private int mMaxInstructions; 11 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/DecomposedInst.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | import diStorm3.Operand; 4 | import diStorm3.Opcodes; 5 | 6 | public class DecomposedInst { 7 | private class ImmVariant { 8 | private long mValue; 9 | private int mSize; 10 | 11 | public long getImm() { 12 | return mValue; 13 | } 14 | 15 | public int getSize() { 16 | return mSize; 17 | } 18 | } 19 | 20 | private class DispVariant { 21 | 22 | private long mDisplacement; 23 | private int mSize; 24 | 25 | public long getDisplacement() { 26 | return mDisplacement; 27 | } 28 | 29 | public int getSize() { 30 | return mSize; 31 | } 32 | } 33 | 34 | private long mAddr; 35 | private int mSize; 36 | private int mFlags; 37 | private int mSegment; 38 | private int mBase, mScale; 39 | private int mOpcode; 40 | public Operand[] mOperands; 41 | public DispVariant mDisp; 42 | public ImmVariant mImm; 43 | private int mUnusedPrefixesMask; 44 | private int mMeta; 45 | private int mRegistersMask; 46 | private int mModifiedFlagsMask; 47 | private int mTestedFlagsMask; 48 | private int mUndefinedFlagsMask; 49 | 50 | public long getAddress() { 51 | return mAddr; 52 | } 53 | public int getSize() { 54 | return mSize; 55 | } 56 | public OpcodeEnum getOpcode() { 57 | return Opcodes.lookup(mOpcode); 58 | } 59 | public int getSegment() { 60 | return mSegment & 0x7f; 61 | } 62 | public boolean isSegmentDefault() { 63 | return (mSegment & 0x80) == 0x80; 64 | } 65 | public int getBase() { 66 | return mBase; 67 | } 68 | public int getScale() { 69 | return mScale; 70 | } 71 | public int getUnusedPrefixesMask() { 72 | return mUnusedPrefixesMask; 73 | } 74 | public int getMeta() { 75 | return mMeta; 76 | } 77 | public int getRegistersMask() { 78 | return mRegistersMask; 79 | } 80 | public int getModifiedFlagsMask() { 81 | return mModifiedFlagsMask; 82 | } 83 | public int getTestedFlagsMask() { 84 | return mTestedFlagsMask; 85 | } 86 | public int getUndefinedFlagsMask() { 87 | return mUndefinedFlagsMask; 88 | } 89 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/DecomposedResult.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | public class DecomposedResult { 4 | public DecomposedResult(int maxInstructions) { 5 | mMaxInstructions = maxInstructions; 6 | mInstructions = null; 7 | } 8 | 9 | public DecomposedInst[] mInstructions; 10 | private int mMaxInstructions; 11 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/Operand.java: -------------------------------------------------------------------------------- 1 | package diStorm3; 2 | 3 | public class Operand { 4 | 5 | public enum OperandType { 6 | None, Reg, Imm, Imm1, Imm2, Disp, Smem, Mem, Pc, Ptr 7 | } 8 | 9 | private int mType; 10 | private int mIndex; 11 | private int mSize; 12 | 13 | public OperandType getType() { 14 | return OperandType.values()[mType]; 15 | } 16 | 17 | public int getIndex() { 18 | return mIndex; 19 | } 20 | 21 | public int getSize() { 22 | return mSize; 23 | } 24 | } -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/distorm/src/diStorm3/distorm3.java: -------------------------------------------------------------------------------- 1 | /* 2 | * diStorm3 JNI 3 | * Gil Dabah, Sep 2010 4 | * 5 | */ 6 | package diStorm3; 7 | import diStorm3.CodeInfo; 8 | import diStorm3.DecodedResult; 9 | import diStorm3.DecomposedResult; 10 | import diStorm3.Opcodes; 11 | 12 | public class distorm3 { 13 | 14 | public enum DecodeType { 15 | Decode16Bits, Decode32Bits, Decode64Bits 16 | } 17 | 18 | public static native void Decompose(CodeInfo ci, DecomposedResult dr); 19 | public static native void Decode(CodeInfo ci, DecodedResult dr); 20 | public static native DecodedInst Format(CodeInfo ci, DecomposedInst di); 21 | 22 | public enum Registers { 23 | RAX, RCX, RDX, RBX, RSP, RBP, RSI, RDI, R8, R9, R10, R11, R12, R13, R14, R15, 24 | EAX, ECX, EDX, EBX, ESP, EBP, ESI, EDI, R8D, R9D, R10D, R11D, R12D, R13D, R14D, R15D, 25 | AX, CX, DX, BX, SP, BP, SI, DI, R8W, R9W, R10W, R11W, R12W, R13W, R14W, R15W, 26 | AL, CL, DL, BL, AH, CH, DH, BH, R8B, R9B, R10B, R11B, R12B, R13B, R14B, R15B, 27 | SPL, BPL, SIL, DIL, 28 | ES, CS, SS, DS, FS, GS, 29 | RIP, 30 | ST0, ST1, ST2, ST3, ST4, ST5, ST6, ST7, 31 | MM0, MM1, MM2, MM3, MM4, MM5, MM6, MM7, 32 | XMM0, XMM1, XMM2, XMM3, XMM4, XMM5, XMM6, XMM7, XMM8, XMM9, XMM10, XMM11, XMM12, XMM13, XMM14, XMM15, 33 | YMM0, YMM1, YMM2, YMM3, YMM4, YMM5, YMM6, YMM7, YMM8, YMM9, YMM10, YMM11, YMM12, YMM13, YMM14, YMM15, 34 | CR0, UNUSED0, CR2, CR3, CR4, UNUSED1, UNUSED2, UNUSED3, CR8, 35 | DR0, DR1, DR2, DR3, UNUSED4, UNUSED5, DR6, DR7 36 | }; 37 | 38 | static { 39 | System.loadLibrary("jdistorm"); 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/jdistorm.h: -------------------------------------------------------------------------------- 1 | /* DO NOT EDIT THIS FILE - it is machine generated */ 2 | #include 3 | /* Header for class Distorm3 */ 4 | 5 | #ifndef _Included_Distorm3 6 | #define _Included_Distorm3 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #define PACKAGE_PREFIX "diStorm3/" 12 | 13 | /* 14 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3 15 | * Method: Decompose 16 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecomposedResult;)V 17 | */ 18 | JNIEXPORT void JNICALL Java_diStorm3_distorm3_Decompose 19 | (JNIEnv *, jclass, jobject, jobject); 20 | 21 | /* 22 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3 23 | * Method: Decode 24 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecodedResult;)V 25 | */ 26 | JNIEXPORT void JNICALL Java_diStorm3_distorm3_Decode 27 | (JNIEnv *, jclass, jobject, jobject); 28 | 29 | /* 30 | * Class: com_reviverstudio_core_disasms_distorm3_Distorm3 31 | * Method: Format 32 | * Signature: (LdiStorm3/CodeInfo;LdiStorm3/DecomposedInst;)LdiStorm3/DecodedInst; 33 | */ 34 | JNIEXPORT jobject JNICALL Java_diStorm3_distorm3_Format 35 | (JNIEnv *, jclass, jobject, jobject); 36 | 37 | #ifdef __cplusplus 38 | } 39 | #endif 40 | #endif 41 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/java/jdistorm.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 10.00 3 | # Visual Studio 2008 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jdistorm", "jdistorm.vcproj", "{AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}" 5 | EndProject 6 | Global 7 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 8 | Debug|x64 = Debug|x64 9 | Release|x64 = Release|x64 10 | EndGlobalSection 11 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 12 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Debug|x64.ActiveCfg = Debug|x64 13 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Debug|x64.Build.0 = Debug|x64 14 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Release|x64.ActiveCfg = Release|x64 15 | {AB6B51F5-79C6-44CA-9D0B-7CB2A009A9AB}.Release|x64.Build.0 = Release|x64 16 | EndGlobalSection 17 | GlobalSection(SolutionProperties) = preSolution 18 | HideSolutionNode = FALSE 19 | EndGlobalSection 20 | EndGlobal 21 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/linux/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # diStorm (Linux Port) / Demo Application Makefile 3 | # 4 | 5 | TARGET = disasm 6 | CC = gcc 7 | CFLAGS = -Wall -O2 -o 8 | 9 | all: disasm 10 | 11 | disasm: 12 | ${CC} ${CFLAGS} ${TARGET} main.c ../../distorm3.a 13 | 14 | clean: 15 | /bin/rm -rf *.o ${TARGET} 16 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/tests/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # diStorm (Linux Port) / Demo Application Makefile 3 | # 4 | 5 | TARGET = disasm 6 | CC = gcc 7 | CFLAGS = -Wall -O2 -I. -o 8 | 9 | all: disasm 10 | 11 | disasm: 12 | ${CC} ${CFLAGS} ${TARGET} main.cpp ../distorm64.a 13 | 14 | clean: 15 | /bin/rm -rf *.o ${TARGET} 16 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/tests/main.cpp: -------------------------------------------------------------------------------- 1 | // diStorm64 library sample 2 | // http://ragestorm.net/distorm/ 3 | // Arkon, Stefan, 2005 4 | 5 | 6 | #include 7 | #include 8 | 9 | #pragma comment(lib, "../../distorm.lib") 10 | 11 | #include "../../include/distorm.h" 12 | 13 | // The number of the array of instructions the decoder function will use to return the disassembled instructions. 14 | // Play with this value for performance... 15 | #define MAX_INSTRUCTIONS (1000) 16 | 17 | int main(int argc, char **argv) 18 | { 19 | _DecodeResult res; 20 | _DInst decodedInstructions[1000]; 21 | _DecodedInst di; 22 | unsigned int decodedInstructionsCount = 0, i = 0; 23 | _OffsetType offset = 0; 24 | unsigned int dver = distorm_version(); 25 | printf("diStorm version: %d.%d.%d\n", (dver >> 16), ((dver) >> 8) & 0xff, dver & 0xff); 26 | 27 | unsigned char rawData[6] = { 28 | 0xC4, 0xE3, 0x79, 0x14, 0xD0, 0x03 29 | }; 30 | 31 | _CodeInfo ci = { 0 }; 32 | ci.codeLen = sizeof(rawData); 33 | ci.code = rawData; 34 | ci.dt = Decode64Bits; 35 | ci.features = 0; 36 | distorm_decompose(&ci, decodedInstructions, 1000, &decodedInstructionsCount); 37 | //distorm_decode(0, rawData, sizeof(rawData), Decode32Bits, &di, 1, &decodedInstructionsCount); 38 | for (int i = 0; i < decodedInstructionsCount; i++) { 39 | distorm_format(&ci, &decodedInstructions[i], &di); 40 | printf("%08I64x (%02d) %-24s %s%s%s\r\n", di.offset, di.size, (char*)di.instructionHex.p, (char*)di.mnemonic.p, di.operands.length != 0 ? " " : "", (char*)di.operands.p); 41 | } 42 | 43 | return 0; 44 | } 45 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/tests/tests.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 16 4 | VisualStudioVersion = 16.0.30011.22 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "tests", "tests.vcxproj", "{C35D3921-227A-432A-BB5D-90ECEBAB08B2}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Debug|x64 = Debug|x64 12 | Release|Win32 = Release|Win32 13 | Release|x64 = Release|x64 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|Win32.ActiveCfg = Debug|Win32 17 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|Win32.Build.0 = Debug|Win32 18 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|x64.ActiveCfg = Debug|x64 19 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Debug|x64.Build.0 = Debug|x64 20 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|Win32.ActiveCfg = Release|Win32 21 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|Win32.Build.0 = Release|Win32 22 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|x64.ActiveCfg = Release|x64 23 | {C35D3921-227A-432A-BB5D-90ECEBAB08B2}.Release|x64.Build.0 = Release|x64 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | GlobalSection(ExtensibilityGlobals) = postSolution 29 | SolutionGuid = {051C92F2-5C59-49A6-B43C-C701C2816520} 30 | EndGlobalSection 31 | EndGlobal 32 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/tests/tests.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | {93995380-89BD-4b04-88EB-625FBE52EBFB} 10 | h;hpp;hxx;hm;inl;inc;xsd 11 | 12 | 13 | {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} 14 | rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms 15 | 16 | 17 | 18 | 19 | Source Files 20 | 21 | 22 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/win32/disasm.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 11.00 2 | # Visual Studio 2010 3 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "disasm", "disasm.vcxproj", "{91227BA8-F7EB-43CC-8C4A-A4944C00567B}" 4 | EndProject 5 | Global 6 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 7 | Debug|Win32 = Debug|Win32 8 | Debug|x64 = Debug|x64 9 | Release|Win32 = Release|Win32 10 | Release|x64 = Release|x64 11 | EndGlobalSection 12 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 13 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|Win32.ActiveCfg = Debug|Win32 14 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|Win32.Build.0 = Debug|Win32 15 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|x64.ActiveCfg = Debug|x64 16 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Debug|x64.Build.0 = Debug|x64 17 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|Win32.ActiveCfg = Release|Win32 18 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|Win32.Build.0 = Release|Win32 19 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|x64.ActiveCfg = Release|x64 20 | {91227BA8-F7EB-43CC-8C4A-A4944C00567B}.Release|x64.Build.0 = Release|x64 21 | EndGlobalSection 22 | GlobalSection(SolutionProperties) = preSolution 23 | HideSolutionNode = FALSE 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/examples/win32/disasm.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {4FC737F1-C7A5-4376-A066-2A32D752A2FF} 6 | cpp;c;cxx;def;odl;idl;hpj;bat;asm;asmx 7 | 8 | 9 | 10 | 11 | Source Files 12 | 13 | 14 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/linux/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # diStorm3 (Linux Port) 3 | # 4 | 5 | TARGET_BASE = libdistorm3.so 6 | COBJS = ../../src/mnemonics.o ../../src/textdefs.o ../../src/prefix.o ../../src/operands.o ../../src/insts.o ../../src/instructions.o ../../src/distorm.o ../../src/decoder.o 7 | CC = gcc 8 | CFLAGS += -fPIC -O2 -Wall -DSUPPORT_64BIT_OFFSET -DDISTORM_STATIC -std=c99 9 | LDFLAGS += -shared 10 | PREFIX = /usr/local 11 | # The lib SONAME version: 12 | LIB_S_VERSION = 3 13 | # The lib real version: 14 | LIB_R_VERSION = 3.4.0 15 | LDFLAGS += -Wl,-soname,${TARGET_BASE}.${LIB_S_VERSION} 16 | DESTDIR = 17 | TARGET_NAME = ${TARGET_BASE}.${LIB_R_VERSION} 18 | 19 | all: clib 20 | 21 | clean: 22 | /bin/rm -rf ../../src/*.o ${TARGET_NAME} ../../distorm3.a ./../*.o 23 | 24 | clib: ${COBJS} 25 | ${CC} ${CFLAGS} ${VERSION} ${COBJS} ${LDFLAGS} -o ${TARGET_NAME} 26 | ar rs ../../distorm3.a ${COBJS} 27 | 28 | install: ${TARGET_NAME} 29 | install -D -s ${TARGET_NAME} ${DESTDIR}${PREFIX}/lib/${TARGET_NAME} 30 | ln -sf ${DESTDIR}${PREFIX}/lib/${TARGET_NAME} ${DESTDIR}${PREFIX}/lib/${TARGET_BASE} 31 | @echo "... running ldconfig might be smart ..." 32 | 33 | .c.o: 34 | ${CC} ${CFLAGS} ${VERSION} -c $< -o $@ 35 | 36 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/mac/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # diStorm3 (Mac Port) 3 | # 4 | 5 | DISTORM_MODE ?= DISTORM_DYNAMIC 6 | TARGET = libdistorm3.dylib 7 | PYTHON_BUILD_DIR = ../../Python/macosx-x86 8 | COBJS = ../../src/mnemonics.o ../../src/textdefs.o ../../src/prefix.o ../../src/operands.o ../../src/insts.o ../../src/instructions.o ../../src/distorm.o ../../src/decoder.o 9 | CC = gcc 10 | CFLAGS = -arch x86_64 -O2 -Wall -fPIC -DSUPPORT_64BIT_OFFSET -D${DISTORM_MODE} 11 | ifeq ($(DISTORM_FAT), 1) 12 | CFLAGS += -arch i386 13 | endif 14 | 15 | all: clib 16 | 17 | clean: 18 | /bin/rm -rf ../../src/*.o ${TARGET} ../../libdistorm3.dylib ../../distorm3.a ../../*.a 19 | 20 | clib: ${COBJS} 21 | ifeq '$(DISTORM_MODE)' 'DISTORM_DYNAMIC' 22 | ${CC} ${CFLAGS} ${VERSION} ${COBJS} -fPIC -dynamiclib -o ${TARGET} 23 | [ -d ${PYTHON_BUILD_DIR} ] && rm -rf ${PYTHON_BUILD_DIR} || true 24 | mkdir ${PYTHON_BUILD_DIR} 25 | cp ${TARGET} ${PYTHON_BUILD_DIR}/ 26 | else 27 | ar rs ../../distorm3.a ${COBJS} 28 | endif 29 | 30 | .c.o: 31 | ${CC} ${CFLAGS} ${VERSION} -c $< -o $@ 32 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/tinycc/Makefile: -------------------------------------------------------------------------------- 1 | # 2 | # diStorm3 (Linux Port) 3 | # 4 | 5 | TARGET_BASE = libdistorm3.so 6 | COBJS = ../../src/mnemonics.o ../../src/textdefs.o ../../src/prefix.o ../../src/operands.o ../../src/insts.o ../../src/instructions.o ../../src/distorm.o ../../src/decoder.o 7 | CC = tcc 8 | CFLAGS += -fPIC -Wall -DSUPPORT_64BIT_OFFSET -DDISTORM_STATIC -std=c99 9 | LDFLAGS += -shared 10 | PREFIX = /usr/local 11 | # The lib SONAME version: 12 | LIB_S_VERSION = 3 13 | # The lib real version: 14 | LIB_R_VERSION = 3.4.0 15 | LDFLAGS += -Wl,-soname,${TARGET_BASE}.${LIB_S_VERSION} 16 | DESTDIR = 17 | TARGET_NAME = ${TARGET_BASE}.${LIB_R_VERSION} 18 | 19 | all: clib 20 | 21 | clean: 22 | /bin/rm -rf ../../src/*.o ${TARGET_NAME} ../../distorm3.a ./../*.o 23 | 24 | clib: ${COBJS} 25 | ${CC} ${CFLAGS} ${VERSION} ${COBJS} ${LDFLAGS} -o ${TARGET_NAME} 26 | tcc -ar rs ../../distorm3.a ${COBJS} 27 | 28 | install: ${TARGET_NAME} 29 | install -D -s ${TARGET_NAME} ${DESTDIR}${PREFIX}/lib/${TARGET_NAME} 30 | ln -sf ${DESTDIR}${PREFIX}/lib/${TARGET_NAME} ${DESTDIR}${PREFIX}/lib/${TARGET_BASE} 31 | @echo "... running ldconfig might be smart ..." 32 | 33 | .c.o: 34 | ${CC} ${CFLAGS} ${VERSION} -c $< -o $@ 35 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/win32/cdistorm.vcxproj.filters: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | {50ac9ad6-0895-4596-b142-1a7fad1b97d5} 6 | cpp;c;cxx;def;odl;idl;hpj;bat;asm 7 | 8 | 9 | {8612ae75-7b41-4557-b23b-d3e14e7f9613} 10 | h;hpp;hxx;hm;inl;inc 11 | 12 | 13 | 14 | 15 | Source Files 16 | 17 | 18 | Source Files 19 | 20 | 21 | Source Files 22 | 23 | 24 | Source Files 25 | 26 | 27 | Source Files 28 | 29 | 30 | Source Files 31 | 32 | 33 | Source Files 34 | 35 | 36 | Source Files 37 | 38 | 39 | 40 | 41 | Header Files 42 | 43 | 44 | Header Files 45 | 46 | 47 | Header Files 48 | 49 | 50 | Header Files 51 | 52 | 53 | Header Files 54 | 55 | 56 | Header Files 57 | 58 | 59 | Header Files 60 | 61 | 62 | Header Files 63 | 64 | 65 | Header Files 66 | 67 | 68 | Header Files 69 | 70 | 71 | Header Files 72 | 73 | 74 | Header Files 75 | 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/win32/distorm.sln: -------------------------------------------------------------------------------- 1 | Microsoft Visual Studio Solution File, Format Version 12.00 2 | # Visual Studio 15 3 | VisualStudioVersion = 15.0.28307.572 4 | MinimumVisualStudioVersion = 10.0.40219.1 5 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "distorm", "cdistorm.vcxproj", "{15051CE1-AB10-4239-973D-01B84F2AD0A9}" 6 | EndProject 7 | Global 8 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 9 | clib|Win32 = clib|Win32 10 | clib|x64 = clib|x64 11 | dll|Win32 = dll|Win32 12 | dll|x64 = dll|x64 13 | EndGlobalSection 14 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 15 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|Win32.ActiveCfg = clib|Win32 16 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|Win32.Build.0 = clib|Win32 17 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|x64.ActiveCfg = clib|x64 18 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.clib|x64.Build.0 = clib|x64 19 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|Win32.ActiveCfg = dll|Win32 20 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|Win32.Build.0 = dll|Win32 21 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|x64.ActiveCfg = dll|x64 22 | {15051CE1-AB10-4239-973D-01B84F2AD0A9}.dll|x64.Build.0 = dll|x64 23 | EndGlobalSection 24 | GlobalSection(SolutionProperties) = preSolution 25 | HideSolutionNode = FALSE 26 | EndGlobalSection 27 | GlobalSection(ExtensibilityGlobals) = postSolution 28 | SolutionGuid = {11B358A5-CF9E-4C14-9F0F-B7DE2C53FA81} 29 | EndGlobalSection 30 | EndGlobal 31 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/win32/resource.h: -------------------------------------------------------------------------------- 1 | //{{NO_DEPENDENCIES}} 2 | // Microsoft Visual C++ generated include file. 3 | // Used by resource.rc 4 | 5 | // Next default values for new objects 6 | // 7 | #ifdef APSTUDIO_INVOKED 8 | #ifndef APSTUDIO_READONLY_SYMBOLS 9 | #define _APS_NEXT_RESOURCE_VALUE 101 10 | #define _APS_NEXT_COMMAND_VALUE 40001 11 | #define _APS_NEXT_CONTROL_VALUE 1001 12 | #define _APS_NEXT_SYMED_VALUE 101 13 | #endif 14 | #endif 15 | //{{NO_DEPENDENCIES}} 16 | // Microsoft Visual C++ generated include file. 17 | // Used by Resource.rc 18 | 19 | // Next default values for new objects 20 | // 21 | #ifdef APSTUDIO_INVOKED 22 | #ifndef APSTUDIO_READONLY_SYMBOLS 23 | #define _APS_NEXT_RESOURCE_VALUE 101 24 | #define _APS_NEXT_COMMAND_VALUE 40001 25 | #define _APS_NEXT_CONTROL_VALUE 1001 26 | #define _APS_NEXT_SYMED_VALUE 101 27 | #endif 28 | #endif 29 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/make/win32/resource.rc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/assess_ext/funchook/distorm/make/win32/resource.rc -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/python/distorm3/__main__.py: -------------------------------------------------------------------------------- 1 | # Based on work by Mario Vilas, http://breakingcode.wordpress.com, licensed under BSD in 2016 2 | 3 | import distorm3 4 | import argparse 5 | 6 | 7 | def parse_args(): 8 | parser = argparse.ArgumentParser() 9 | parser.add_argument( 10 | "--b16", 11 | help="80286 decoding", 12 | action="store_const", 13 | dest="dt", 14 | const=distorm3.Decode16Bits, 15 | ) 16 | parser.add_argument( 17 | "--b32", 18 | help="IA-32 decoding [default]", 19 | action="store_const", 20 | dest="dt", 21 | const=distorm3.Decode32Bits, 22 | ) 23 | parser.add_argument( 24 | "--b64", 25 | help="AMD64 decoding", 26 | action="store_const", 27 | dest="dt", 28 | const=distorm3.Decode64Bits, 29 | ) 30 | parser.add_argument("file",) 31 | parser.add_argument( 32 | "offset", type=int, nargs="?", 33 | ) 34 | parser.set_defaults(dt=distorm3.Decode32Bits) 35 | args = parser.parse_args() 36 | return args 37 | 38 | 39 | def main(): 40 | args = parse_args() 41 | offset = args.offset 42 | 43 | # Read the code from the file 44 | with open(args.file, "rb") as infp: 45 | code = infp.read() 46 | 47 | # Print each decoded instruction 48 | # This shows how to use the DecodeGenerator 49 | iterable = distorm3.DecodeGenerator(offset, code, args.dt) 50 | for (offset, size, instruction, hexdump) in iterable: 51 | print("%.8x: %-32s %s" % (offset, hexdump, instruction)) 52 | 53 | # It could also be used as a returned list: 54 | # l = distorm3.Decode(offset, code, options.dt) 55 | # for (offset, size, instruction, hexdump) in l: 56 | # print("%.8x: %-32s %s" % (offset, hexdump, instruction)) 57 | 58 | 59 | if __name__ == "__main__": 60 | main() 61 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/python/python_module_init.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #if PY_MAJOR_VERSION == 2 5 | PyMODINIT_FUNC init_distorm3(void) 6 | { 7 | (void)Py_InitModule("_distorm3", NULL); 8 | } 9 | #else 10 | static struct PyModuleDef _distorm3_module = { 11 | PyModuleDef_HEAD_INIT, 12 | "_distorm3", 13 | NULL, 14 | -1, 15 | NULL, 16 | }; 17 | 18 | PyMODINIT_FUNC PyInit__distorm3(void) 19 | { 20 | PyObject *m; 21 | 22 | m = PyModule_Create(&_distorm3_module); 23 | if (m == NULL) 24 | return NULL; 25 | 26 | return m; 27 | } 28 | #endif 29 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/setup.cfg: -------------------------------------------------------------------------------- 1 | [install] 2 | force=1 3 | compile=1 4 | optimize=1 5 | 6 | [bdist_wininst] 7 | user-access-control=auto 8 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | import os 4 | import os.path 5 | from glob import glob 6 | from setuptools import Extension, setup 7 | 8 | def main(): 9 | # Just in case we are being called from a different directory 10 | cwd = os.path.dirname(__file__) 11 | if cwd: 12 | os.chdir(cwd) 13 | 14 | distorm_module = Extension( 15 | "_distorm3", 16 | sources=sorted(glob('src/*.c')) + ["python/python_module_init.c"], 17 | include_dirs=['src', 'include'], 18 | define_macros=[('SUPPORT_64BIT_OFFSET', None), ('DISTORM_DYNAMIC', None)], 19 | ) 20 | 21 | options = { 22 | # Setup instructions 23 | 'requires' : ['ctypes'], 24 | 'provides' : ['distorm3'], 25 | 'packages' : ['distorm3'], 26 | 'package_dir' : { '' : 'python' }, 27 | 'ext_modules' : [distorm_module], 28 | # Metadata 29 | 'name' : 'distorm3', 30 | 'version' : '3.5.2', 31 | 'description' : 'The goal of diStorm3 is to decode x86/AMD64' \ 32 | ' binary streams and return a structure that' \ 33 | ' describes each instruction.', 34 | 'long_description' : ( 35 | 'Powerful Disassembler Library For AMD64\n' 36 | 'by Gil Dabah (distorm@gmail.com)\n' 37 | '\n' 38 | 'Python bindings by Mario Vilas (mvilas@gmail.com)' 39 | ), 40 | 'author' : 'Gil Dabah', 41 | 'author_email' : 'distorm@gmail.com', 42 | 'maintainer' : 'Gil Dabah', 43 | 'maintainer_email' : 'distorm@gmail.com', 44 | 'url' : 'https://github.com/gdabah/distorm/', 45 | 'download_url' : 'https://github.com/gdabah/distorm/', 46 | 'platforms' : ['cygwin', 'win', 'linux', 'macosx'], 47 | 'classifiers' : [ 48 | 'License :: OSI Approved :: BSD License', 49 | 'Development Status :: 5 - Production/Stable', 50 | 'Intended Audience :: Developers', 51 | 'Natural Language :: English', 52 | 'Operating System :: Microsoft :: Windows', 53 | 'Operating System :: MacOS :: MacOS X', 54 | 'Operating System :: POSIX :: Linux', 55 | 'Programming Language :: Python :: 3.5', 56 | 'Topic :: Software Development :: Disassemblers', 57 | 'Topic :: Software Development :: Libraries :: Python Modules', 58 | ] 59 | } 60 | 61 | # Call the setup function 62 | setup(**options) 63 | 64 | if __name__ == '__main__': 65 | main() 66 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/decoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | decoder.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef DECODER_H 13 | #define DECODER_H 14 | 15 | #include "config.h" 16 | 17 | typedef unsigned int _iflags; 18 | 19 | _DecodeResult decode_internal(_CodeInfo* _ci, int supportOldIntr, _DInst result[], unsigned int maxResultCount, unsigned int* usedInstructionsCount); 20 | 21 | #endif /* DECODER_H */ 22 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/insts.h: -------------------------------------------------------------------------------- 1 | /* 2 | insts.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef INSTS_H 13 | #define INSTS_H 14 | 15 | #include "instructions.h" 16 | 17 | 18 | /* Flags Table */ 19 | extern _iflags FlagsTable[]; 20 | 21 | /* Root Trie DB */ 22 | extern _InstSharedInfo InstSharedInfoTable[]; 23 | extern _InstInfo InstInfos[]; 24 | extern _InstInfoEx InstInfosEx[]; 25 | extern _InstNode InstructionsTree[]; 26 | 27 | /* 3DNow! Trie DB */ 28 | extern _InstNode Table_0F_0F; 29 | /* AVX related: */ 30 | extern _InstNode Table_0F, Table_0F_38, Table_0F_3A; 31 | 32 | /* 33 | * The inst_lookup will return on of these two instructions according to the specified decoding mode. 34 | * ARPL or MOVSXD on 64 bits is one byte instruction at index 0x63. 35 | */ 36 | extern _InstInfo II_MOVSXD; 37 | 38 | /* 39 | * The NOP instruction can be prefixed by REX in 64bits, therefore we have to decide in runtime whether it's an XCHG or NOP instruction. 40 | * If 0x90 is prefixed by a usable REX it will become XCHG, otherwise it will become a NOP. 41 | * Also note that if it's prefixed by 0xf3, it becomes a Pause. 42 | */ 43 | extern _InstInfo II_NOP; 44 | extern _InstInfo II_PAUSE; 45 | 46 | /* 47 | * RDRAND and VMPTRLD share same 2.3 bytes opcode, and then alternates on the MOD bits, 48 | * RDRAND is OT_FULL_REG while VMPTRLD is OT_MEM, and there's no such mixed type. 49 | * So a hack into the inst_lookup was added for this decision, the DB isn't flexible enough. :( 50 | */ 51 | extern _InstInfo II_RDRAND; 52 | 53 | /* 54 | * Used for letting the extract operand know the type of operands without knowing the 55 | * instruction itself yet, because of the way those instructions work. 56 | * See function instructions.c!inst_lookup_3dnow. 57 | */ 58 | extern _InstInfo II_3DNOW; 59 | 60 | /* Helper tables for pseudo compare mnemonics. */ 61 | extern uint16_t CmpMnemonicOffsets[8]; /* SSE */ 62 | extern uint16_t VCmpMnemonicOffsets[32]; /* AVX */ 63 | 64 | #endif /* INSTS_H */ 65 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/operands.h: -------------------------------------------------------------------------------- 1 | /* 2 | operands.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef OPERANDS_H 13 | #define OPERANDS_H 14 | 15 | #include "config.h" 16 | #include "decoder.h" 17 | #include "prefix.h" 18 | #include "instructions.h" 19 | 20 | int operands_extract(_CodeInfo* ci, _DInst* di, _InstInfo* ii, 21 | _iflags instFlags, _OpType type, 22 | unsigned int modrm, _PrefixState* ps, _DecodeType effOpSz, 23 | _DecodeType effAdrSz, _Operand* op); 24 | 25 | #endif /* OPERANDS_H */ 26 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/prefix.c: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/assess_ext/funchook/distorm/src/prefix.c -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/prefix.h: -------------------------------------------------------------------------------- 1 | /* 2 | prefix.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef PREFIX_H 13 | #define PREFIX_H 14 | 15 | #include "config.h" 16 | #include "decoder.h" 17 | 18 | 19 | /* Specifies the type of the extension prefix, such as: REX, 2 bytes VEX, 3 bytes VEX. */ 20 | typedef enum {PET_NONE = 0, PET_REX, PET_VEX2BYTES, PET_VEX3BYTES} _PrefixExtType; 21 | 22 | /* Specifies an index into a table of prefixes by their type. */ 23 | typedef enum {PFXIDX_NONE = -1, PFXIDX_REX, PFXIDX_LOREP, PFXIDX_SEG, PFXIDX_OP_SIZE, PFXIDX_ADRS, PFXIDX_MAX} _PrefixIndexer; 24 | 25 | /* 26 | * This holds the prefixes state for the current instruction we decode. 27 | * decodedPrefixes includes all specific prefixes that the instruction got. 28 | * start is a pointer to the first prefix to take into account. 29 | * last is a pointer to the last byte we scanned. 30 | * Other pointers are used to keep track of prefixes positions and help us know if they appeared already and where. 31 | */ 32 | typedef struct { 33 | _iflags decodedPrefixes, usedPrefixes; 34 | /* Number of prefixes scanned for current instruction, including VEX! */ 35 | unsigned int count; 36 | uint16_t unusedPrefixesMask; 37 | /* Holds the offset to the prefix byte by its type. */ 38 | uint16_t pfxIndexer[PFXIDX_MAX]; 39 | _PrefixExtType prefixExtType; 40 | /* Indicates whether the operand size prefix (0x66) was used as a mandatory prefix. */ 41 | int isOpSizeMandatory; 42 | /* If VEX prefix is used, store the VEX.vvvv field. */ 43 | unsigned int vexV; 44 | /* The fields B/X/R/W/L of REX and VEX are stored together in this byte. */ 45 | unsigned int vrex; 46 | const uint8_t* vexPos; 47 | } _PrefixState; 48 | 49 | /* 50 | * Intel supports 6 types of prefixes, whereas AMD supports 5 types (lock is seperated from rep/nz). 51 | * REX is the fifth prefix type, this time I'm based on AMD64. 52 | * VEX is the 6th, though it can't be repeated. 53 | */ 54 | #define MAX_PREFIXES (5) 55 | 56 | extern int PrefixTables[256 * 2]; 57 | 58 | _INLINE_ int prefixes_is_valid(unsigned char ch, _DecodeType dt) 59 | { 60 | /* The predicate selects (branchlessly) second half table for 64 bits otherwise selects first half. */ 61 | return PrefixTables[ch + ((dt >> 1) << 8)]; 62 | } 63 | 64 | /* Ignore a specific prefix type. */ 65 | _INLINE_ void prefixes_ignore(_PrefixState* ps, _PrefixIndexer pi) 66 | { 67 | /* 68 | * If that type of prefix appeared already, set the bit of that *former* prefix. 69 | * Anyway, set the new index of that prefix type to the current index, so next time we know its position. 70 | */ 71 | ps->unusedPrefixesMask |= ps->pfxIndexer[pi]; 72 | } 73 | 74 | void prefixes_ignore_all(_PrefixState* ps); 75 | uint16_t prefixes_set_unused_mask(_PrefixState* ps); 76 | void prefixes_decode(_CodeInfo* ci, _PrefixState* ps); 77 | void prefixes_use_segment(_iflags defaultSeg, _PrefixState* ps, _DecodeType dt, _DInst* di); 78 | 79 | #endif /* PREFIX_H */ 80 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/textdefs.c: -------------------------------------------------------------------------------- 1 | /* 2 | textdefs.c 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #include "textdefs.h" 13 | 14 | #ifndef DISTORM_LIGHT 15 | 16 | static uint8_t Nibble2ChrTable[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'}; 17 | #define NIBBLE_TO_CHR Nibble2ChrTable[t] 18 | 19 | void str_hex(_WString* s, const uint8_t* buf, unsigned int len) 20 | { 21 | /* 256 * 2 : 2 chars per byte value. */ 22 | static const char* TextBTable = 23 | "000102030405060708090a0b0c0d0e0f" \ 24 | "101112131415161718191a1b1c1d1e1f" \ 25 | "202122232425262728292a2b2c2d2e2f" \ 26 | "303132333435363738393a3b3c3d3e3f" \ 27 | "404142434445464748494a4b4c4d4e4f" \ 28 | "505152535455565758595a5b5c5d5e5f" \ 29 | "606162636465666768696a6b6c6d6e6f" \ 30 | "707172737475767778797a7b7c7d7e7f" \ 31 | "808182838485868788898a8b8c8d8e8f" \ 32 | "909192939495969798999a9b9c9d9e9f" \ 33 | "a0a1a2a3a4a5a6a7a8a9aaabacadaeaf" \ 34 | "b0b1b2b3b4b5b6b7b8b9babbbcbdbebf" \ 35 | "c0c1c2c3c4c5c6c7c8c9cacbcccdcecf" \ 36 | "d0d1d2d3d4d5d6d7d8d9dadbdcdddedf" \ 37 | "e0e1e2e3e4e5e6e7e8e9eaebecedeeef" \ 38 | "f0f1f2f3f4f5f6f7f8f9fafbfcfdfeff"; 39 | 40 | unsigned int i = 0; 41 | /* Length is at least 1, enter loop. */ 42 | s->length = len * 2; 43 | s->p[len * 2] = 0; 44 | do { 45 | RSHORT(&s->p[i]) = RSHORT(&TextBTable[(*buf) * 2]); 46 | buf++; 47 | i += 2; 48 | } while (i < len * 2); 49 | } 50 | 51 | #ifdef SUPPORT_64BIT_OFFSET 52 | 53 | void str_int_impl(unsigned char** s, uint64_t x) 54 | { 55 | int8_t* buf; 56 | int shift = 0; 57 | OFFSET_INTEGER t = x; 58 | 59 | buf = (int8_t*)*s; 60 | 61 | *buf++ = '0'; 62 | *buf++ = 'x'; 63 | 64 | if (x == 0) { 65 | *buf = '0'; 66 | *s += 3; 67 | return; 68 | } 69 | 70 | do { 71 | t >>= 4; 72 | shift += 4; 73 | } while (t); 74 | 75 | do { 76 | shift -= 4; 77 | t = (x >> shift) & 0xf; 78 | *buf++ = NIBBLE_TO_CHR; 79 | } while (shift > 0); 80 | 81 | *s = (unsigned char*)buf; 82 | } 83 | 84 | #else 85 | 86 | void str_int_impl(unsigned char** s, uint8_t src[8]) 87 | { 88 | int8_t* buf; 89 | int i = 0, shift = 0; 90 | uint32_t x = RULONG(&src[sizeof(int32_t)]); 91 | int t; 92 | 93 | buf = (int8_t*)*s; 94 | buf[0] = '0'; 95 | buf[1] = 'x'; 96 | buf += 2; 97 | 98 | for (shift = 28; shift != -4; shift -= 4) { 99 | t = (x >> shift) & 0xf; 100 | if (i | t) buf[i++] = NIBBLE_TO_CHR; 101 | } 102 | 103 | x = RULONG(src); 104 | for (shift = 28; shift != 0; shift -= 4) { 105 | t = (x >> shift) & 0xf; 106 | if (i | t) buf[i++] = NIBBLE_TO_CHR; 107 | } 108 | t = x & 0xf; 109 | buf[i++] = NIBBLE_TO_CHR; 110 | 111 | *s += (size_t)(i + 2); 112 | } 113 | 114 | #endif /* SUPPORT_64BIT_OFFSET */ 115 | 116 | #endif /* DISTORM_LIGHT */ 117 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/textdefs.h: -------------------------------------------------------------------------------- 1 | /* 2 | textdefs.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef TEXTDEFS_H 13 | #define TEXTDEFS_H 14 | 15 | #include "config.h" 16 | #include "wstring.h" 17 | 18 | #ifndef DISTORM_LIGHT 19 | 20 | #define PLUS_DISP_CHR '+' 21 | #define MINUS_DISP_CHR '-' 22 | #define OPEN_CHR '[' 23 | #define CLOSE_CHR ']' 24 | #define SP_CHR ' ' 25 | #define SEG_OFF_CHR ':' 26 | 27 | /* 28 | Naming Convention: 29 | 30 | * get - returns a pointer to a string. 31 | * str - concatenates to string. 32 | 33 | * hex - means the function is used for hex dump (number is padded to required size) - Little Endian output. 34 | * code - means the function is used for disassembled instruction - Big Endian output. 35 | * off - means the function is used for 64bit offset - Big Endian output. 36 | 37 | * h - '0x' in front of the string. 38 | 39 | * b - byte 40 | * dw - double word (can be used for word also) 41 | * qw - quad word 42 | 43 | * all numbers are in HEX. 44 | */ 45 | 46 | void str_hex(_WString* s, const uint8_t* buf, unsigned int len); 47 | 48 | #ifdef SUPPORT_64BIT_OFFSET 49 | #define str_int(s, x) str_int_impl((s), (x)) 50 | void str_int_impl(unsigned char** s, uint64_t x); 51 | #else 52 | #define str_int(s, x) str_int_impl((s), (uint8_t*)&(x)) 53 | void str_int_impl(unsigned char** s, uint8_t src[8]); 54 | #endif 55 | 56 | #endif /* DISTORM_LIGHT */ 57 | 58 | #endif /* TEXTDEFS_H */ 59 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/wstring.h: -------------------------------------------------------------------------------- 1 | /* 2 | wstring.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef WSTRING_H 13 | #define WSTRING_H 14 | 15 | #include "config.h" 16 | #include "../include/mnemonics.h" 17 | 18 | #ifndef DISTORM_LIGHT 19 | 20 | _INLINE_ void strcat_WSR(unsigned char** str, const _WRegister* reg) 21 | { 22 | /* 23 | * Longest register name is YMM15 - 5 characters, 24 | * Copy 8 so compiler can do a QWORD move. 25 | * We copy nul termination and fix the length, so it's okay to copy more to the output buffer. 26 | * There's a sentinel register to make sure we don't read past the end of the registers table. 27 | */ 28 | memcpy((int8_t*)*str, (const int8_t*)reg->p, 8); 29 | *str += reg->length; 30 | } 31 | 32 | #define strfinalize_WS(s, end) do { *end = 0; s.length = (unsigned int)((size_t)end - (size_t)s.p); } while (0) 33 | #define chrcat_WS(s, ch) do { *s = ch; s += 1; } while (0) 34 | #define strcat_WS(s, buf, copylen, advancelen) do { memcpy((int8_t*)s, buf, copylen); s += advancelen; } while(0) 35 | 36 | #endif /* DISTORM_LIGHT */ 37 | 38 | #endif /* WSTRING_H */ 39 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/src/x86defs.h: -------------------------------------------------------------------------------- 1 | /* 2 | x86defs.h 3 | 4 | diStorm3 - Powerful disassembler for X86/AMD64 5 | http://ragestorm.net/distorm/ 6 | distorm at gmail dot com 7 | Copyright (C) 2003-2021 Gil Dabah 8 | This library is licensed under the BSD license. See the file COPYING. 9 | */ 10 | 11 | 12 | #ifndef X86DEFS_H 13 | #define X86DEFS_H 14 | 15 | 16 | #define SEG_REGS_MAX (6) 17 | #define CREGS_MAX (9) 18 | #define DREGS_MAX (8) 19 | 20 | /* Maximum instruction size, including prefixes */ 21 | #define INST_MAXIMUM_SIZE (15) 22 | 23 | /* Maximum range of imm8 (comparison type) of special SSE CMP instructions. */ 24 | #define INST_CMP_MAX_RANGE (8) 25 | 26 | /* Maximum range of imm8 (comparison type) of special AVX VCMP instructions. */ 27 | #define INST_VCMP_MAX_RANGE (32) 28 | 29 | /* Wait instruction byte code. */ 30 | #define INST_WAIT_INDEX (0x9b) 31 | 32 | /* Lea instruction byte code. */ 33 | #define INST_LEA_INDEX (0x8d) 34 | 35 | /* NOP/XCHG instruction byte code. */ 36 | #define INST_NOP_INDEX (0x90) 37 | 38 | /* ARPL/MOVSXD instruction byte code. */ 39 | #define INST_ARPL_INDEX (0x63) 40 | 41 | /* 42 | * Minimal MODR/M value of divided instructions. 43 | * It's 0xc0, two MSBs set, which indicates a general purpose register is used too. 44 | */ 45 | #define INST_DIVIDED_MODRM (0xc0) 46 | 47 | /* This is the escape byte value used for 3DNow! instructions. */ 48 | #define _3DNOW_ESCAPE_BYTE (0x0f) 49 | 50 | #define PREFIX_LOCK (0xf0) 51 | #define PREFIX_REPNZ (0xf2) 52 | #define PREFIX_REP (0xf3) 53 | #define PREFIX_CS (0x2e) 54 | #define PREFIX_SS (0x36) 55 | #define PREFIX_DS (0x3e) 56 | #define PREFIX_ES (0x26) 57 | #define PREFIX_FS (0x64) 58 | #define PREFIX_GS (0x65) 59 | #define PREFIX_OP_SIZE (0x66) 60 | #define PREFIX_ADDR_SIZE (0x67) 61 | #define PREFIX_VEX2b (0xc5) 62 | #define PREFIX_VEX3b (0xc4) 63 | 64 | /* REX prefix value range, 64 bits mode decoding only. */ 65 | #define PREFIX_REX_LOW (0x40) 66 | #define PREFIX_REX_HI (0x4f) 67 | /* In order to use the extended GPR's we have to add 8 to the Modr/M info values. */ 68 | #define EX_GPR_BASE (8) 69 | 70 | /* Mask for REX and VEX features: */ 71 | /* Base */ 72 | #define PREFIX_EX_B (1) 73 | /* Index */ 74 | #define PREFIX_EX_X (2) 75 | /* Register */ 76 | #define PREFIX_EX_R (4) 77 | /* Operand Width */ 78 | #define PREFIX_EX_W (8) 79 | /* Vector Lengh */ 80 | #define PREFIX_EX_L (0x10) 81 | 82 | #endif /* X86DEFS_H */ 83 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/distorm/test-deps/yasm-1.3.0-win64.exe: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/assess_ext/funchook/distorm/test-deps/yasm-1.3.0-win64.exe -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/src/cmake_config.h.in: -------------------------------------------------------------------------------- 1 | #cmakedefine _GNU_SOURCE 2 | #cmakedefine GNU_SPECIFIC_STRERROR_R 1 3 | #cmakedefine DISASM_CAPSTONE 1 4 | #cmakedefine DISASM_DISTORM 1 5 | #cmakedefine DISASM_ZYDIS 1 6 | #define SIZEOF_VOID_P @CMAKE_SIZEOF_VOID_P@ 7 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/src/funchook_arm64.h: -------------------------------------------------------------------------------- 1 | /* -*- indent-tabs-mode: nil -*- 2 | * 3 | * This file is part of Funchook. 4 | * https://github.com/kubo/funchook 5 | * 6 | * Funchook is free software: you can redistribute it and/or modify it 7 | * under the terms of the GNU General Public License as published by the 8 | * Free Software Foundation, either version 2 of the License, or (at your 9 | * option) any later version. 10 | * 11 | * As a special exception, the copyright holders of this library give you 12 | * permission to link this library with independent modules to produce an 13 | * executable, regardless of the license terms of these independent 14 | * modules, and to copy and distribute the resulting executable under 15 | * terms of your choice, provided that you also meet, for each linked 16 | * independent module, the terms and conditions of the license of that 17 | * module. An independent module is a module which is not derived from or 18 | * based on this library. If you modify this library, you may extend this 19 | * exception to your version of the library, but you are not obliged to 20 | * do so. If you do not wish to do so, delete this exception statement 21 | * from your version. 22 | * 23 | * Funchook is distributed in the hope that it will be useful, but WITHOUT 24 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 25 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 26 | * for more details. 27 | * 28 | * You should have received a copy of the GNU General Public License 29 | * along with Funchook. If not, see . 30 | */ 31 | #ifndef FUNCHOOK_ARM64_H 32 | #define FUNCHOOK_ARM64_H 1 33 | 34 | #define FUNCHOOK_ARM64_REG_X9 (1u<<9) 35 | #define FUNCHOOK_ARM64_REG_X10 (1u<<10) 36 | #define FUNCHOOK_ARM64_REG_X11 (1u<<11) 37 | #define FUNCHOOK_ARM64_REG_X12 (1u<<12) 38 | #define FUNCHOOK_ARM64_REG_X13 (1u<<13) 39 | #define FUNCHOOK_ARM64_REG_X14 (1u<<14) 40 | #define FUNCHOOK_ARM64_REG_X15 (1u<<15) 41 | #define FUNCHOOK_ARM64_CORRUPTIBLE_REGS (FUNCHOOK_ARM64_REG_X9 \ 42 | | FUNCHOOK_ARM64_REG_X10 | FUNCHOOK_ARM64_REG_X11 \ 43 | | FUNCHOOK_ARM64_REG_X12 | FUNCHOOK_ARM64_REG_X13 \ 44 | | FUNCHOOK_ARM64_REG_X14 | FUNCHOOK_ARM64_REG_X15) 45 | 46 | typedef enum { 47 | FUNCHOOK_ARM64_INSN_OTHER = 0, 48 | FUNCHOOK_ARM64_INSN_ADR, 49 | FUNCHOOK_ARM64_INSN_ADRP, 50 | FUNCHOOK_ARM64_INSN_B, 51 | FUNCHOOK_ARM64_INSN_BL, 52 | FUNCHOOK_ARM64_INSN_B_cond, 53 | FUNCHOOK_ARM64_INSN_CBNZ, 54 | FUNCHOOK_ARM64_INSN_CBZ, 55 | FUNCHOOK_ARM64_INSN_LDR, 56 | FUNCHOOK_ARM64_INSN_LDRSW, 57 | FUNCHOOK_ARM64_INSN_PRFM, 58 | FUNCHOOK_ARM64_INSN_TBNZ, 59 | FUNCHOOK_ARM64_INSN_TBZ, 60 | } funchook_arm64_insn_id_t; 61 | 62 | #define MAX_INSN_CHECK_SIZE 64 63 | #define JUMP32_SIZE 2 64 | #define JUMP64_SIZE 4 65 | #define LITERAL_POOL_OFFSET (3 * JUMP32_SIZE + 2) 66 | #define LITERAL_POOL_NUM (JUMP32_SIZE + 1) 67 | #define TRAMPOLINE_SIZE (LITERAL_POOL_OFFSET + 2 * LITERAL_POOL_NUM) 68 | 69 | #define FUNCHOOK_ENTRY_AT_PAGE_BOUNDARY 1 70 | 71 | typedef uint32_t insn_t; 72 | 73 | typedef struct funchook_entry { 74 | uint32_t transit[JUMP64_SIZE]; 75 | void *target_func; 76 | void *hook_func; 77 | uint32_t trampoline[TRAMPOLINE_SIZE]; 78 | uint32_t old_code[JUMP32_SIZE]; 79 | uint32_t new_code[JUMP32_SIZE]; 80 | } funchook_entry_t; 81 | 82 | typedef struct { 83 | int dummy; 84 | } ip_displacement_t; 85 | 86 | typedef struct { 87 | funchook_arm64_insn_id_t insn_id; 88 | uint32_t regs; 89 | } funchook_insn_info_t; 90 | 91 | #endif 92 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/src/funchook_x86.h: -------------------------------------------------------------------------------- 1 | /* -*- indent-tabs-mode: nil -*- 2 | * 3 | * This file is part of Funchook. 4 | * https://github.com/kubo/funchook 5 | * 6 | * Funchook is free software: you can redistribute it and/or modify it 7 | * under the terms of the GNU General Public License as published by the 8 | * Free Software Foundation, either version 2 of the License, or (at your 9 | * option) any later version. 10 | * 11 | * As a special exception, the copyright holders of this library give you 12 | * permission to link this library with independent modules to produce an 13 | * executable, regardless of the license terms of these independent 14 | * modules, and to copy and distribute the resulting executable under 15 | * terms of your choice, provided that you also meet, for each linked 16 | * independent module, the terms and conditions of the license of that 17 | * module. An independent module is a module which is not derived from or 18 | * based on this library. If you modify this library, you may extend this 19 | * exception to your version of the library, but you are not obliged to 20 | * do so. If you do not wish to do so, delete this exception statement 21 | * from your version. 22 | * 23 | * Funchook is distributed in the hope that it will be useful, but WITHOUT 24 | * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 25 | * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 26 | * for more details. 27 | * 28 | * You should have received a copy of the GNU General Public License 29 | * along with Funchook. If not, see . 30 | */ 31 | #ifndef FUNCHOOK_X86_H 32 | #define FUNCHOOK_X86_H 1 33 | 34 | #define MAX_INSN_LEN 16 35 | #define MAX_INSN_CHECK_SIZE 256 36 | 37 | #define JUMP32_SIZE 5 38 | #ifdef CPU_X86_64 39 | #define JUMP64_SIZE 14 40 | #endif 41 | 42 | #define TRAMPOLINE_SIZE (JUMP32_SIZE + (MAX_INSN_LEN - 1) + JUMP32_SIZE) 43 | 44 | typedef uint8_t insn_t; 45 | 46 | typedef struct funchook_entry { 47 | void *target_func; 48 | void *hook_func; 49 | uint8_t trampoline[TRAMPOLINE_SIZE]; 50 | uint8_t old_code[JUMP32_SIZE]; 51 | uint8_t new_code[JUMP32_SIZE]; 52 | #ifdef CPU_X86_64 53 | uint8_t transit[JUMP64_SIZE]; 54 | #endif 55 | } funchook_entry_t; 56 | 57 | typedef struct { 58 | const insn_t *dst_addr; 59 | intptr_t src_addr_offset; 60 | intptr_t pos_offset; 61 | } ip_displacement_entry_t; 62 | 63 | typedef struct { 64 | ip_displacement_entry_t disp[2]; 65 | } ip_displacement_t; 66 | 67 | #endif 68 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | cmake_minimum_required(VERSION 3.5) 2 | project(libfunchook_test LANGUAGES C ASM) 3 | 4 | set(FUNCHOOK_CPU ${CMAKE_SYSTEM_PROCESSOR}) 5 | 6 | if (FUNCHOOK_CPU STREQUAL AMD64) 7 | set(FUNCHOOK_CPU "x86_64") 8 | endif () 9 | 10 | if (FUNCHOOK_CPU STREQUAL x86_64) 11 | if (CMAKE_SIZEOF_VOID_P EQUAL "4") 12 | set(FUNCHOOK_CPU "x86") 13 | endif () 14 | endif () 15 | 16 | if (FUNCHOOK_CPU MATCHES "i.86") 17 | set(FUNCHOOK_CPU "x86") 18 | endif () 19 | 20 | set(TEST_EXE_SOURCES test_main.c) 21 | if (FUNCHOOK_CPU STREQUAL x86) 22 | set(TEST_EXE_SOURCES ${TEST_EXE_SOURCES} ${FUNCHOOK_CPU}_test.S) 23 | endif () 24 | 25 | 26 | if (MSVC) 27 | enable_language(ASM_MASM) 28 | set(FUNCHOOK_ASM_SUFFIX _masm.asm) 29 | else () 30 | set(FUNCHOOK_ASM_SUFFIX _gas.S) 31 | endif () 32 | 33 | add_library(funchook_test SHARED libfunchook_test.c libfunchook_test_${FUNCHOOK_CPU}${FUNCHOOK_ASM_SUFFIX}) 34 | if (MSVC) 35 | set_target_properties(funchook_test PROPERTIES OUTPUT_NAME funchook_test_dll) 36 | if (CMAKE_SIZEOF_VOID_P MATCHES "4") 37 | set_source_files_properties(libfunchook_test_x86_masm.asm PROPERTIES COMPILE_FLAGS /safeseh) 38 | endif () 39 | else () 40 | set_target_properties(funchook_test PROPERTIES SUFFIX ".so") 41 | endif () 42 | 43 | set(FUNCHOOK_TEST_LIBS funchook_test) 44 | if (UNIX) 45 | set(FUNCHOOK_TEST_LIBS ${FUNCHOOK_TEST_LIBS} dl) 46 | endif () 47 | 48 | if (FUNCHOOK_BUILD_SHARED) 49 | add_executable(funchook_test_shared ${TEST_EXE_SOURCES}) 50 | target_link_libraries(funchook_test_shared PRIVATE funchook-shared ${FUNCHOOK_TEST_LIBS}) 51 | if (UNIX) 52 | set_target_properties(funchook_test_shared PROPERTIES LINK_FLAGS -rdynamic) 53 | endif () 54 | if (WIN32) 55 | add_custom_command(TARGET funchook_test_shared POST_BUILD COMMAND ${CMAKE_COMMAND} -E copy $ $) 56 | endif () 57 | add_test(NAME funchook_test_shared COMMAND $) 58 | endif () 59 | 60 | if (FUNCHOOK_BUILD_STATIC) 61 | add_executable(funchook_test_static ${TEST_EXE_SOURCES}) 62 | target_link_libraries(funchook_test_static PRIVATE funchook-static ${FUNCHOOK_TEST_LIBS}) 63 | if (UNIX) 64 | set_target_properties(funchook_test_static PROPERTIES LINK_FLAGS -rdynamic) 65 | endif () 66 | add_test(NAME funchook_test_static COMMAND $) 67 | endif () 68 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test.c: -------------------------------------------------------------------------------- 1 | #ifdef WIN32 2 | #define DLLEXPORT __declspec(dllexport) 3 | #else 4 | #define DLLEXPORT 5 | #endif 6 | 7 | static int val_in_dll; 8 | 9 | DLLEXPORT void set_val_in_dll(int val) 10 | { 11 | val_in_dll = val; 12 | } 13 | 14 | DLLEXPORT int get_val_in_dll() 15 | { 16 | return val_in_dll; 17 | } 18 | 19 | #define S(suffix) DLLEXPORT int dllfunc_##suffix(int a, int b) { return a * b + suffix; } 20 | #include "suffix.list" 21 | #undef S 22 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test_aarch64_gas.S: -------------------------------------------------------------------------------- 1 | .arch armv8-a 2 | .file "libfunchook_test_aarch64_gas.S" 3 | .text 4 | .align 2 5 | .p2align 3,,7 6 | 7 | test_data: 8 | .8byte 0x1020304050607080, 0x0102030405060708 9 | 10 | call_get_val_in_dll: 11 | .global call_get_val_in_dll 12 | .type call_get_val_in_dll, %function 13 | stp x29, x30, [sp, -16]! 14 | bl get_val_in_dll 15 | ldp x29, x30, [sp], 16 16 | ret 17 | 18 | jump_get_val_in_dll: 19 | .global jump_get_val_in_dll 20 | .type jump_get_val_in_dll, %function 21 | b get_val_in_dll 22 | 23 | arm64_test_adr: 24 | .global arm64_test_adr 25 | .type arm64_test_adr, %function 26 | adr x9, test_data 27 | ldr x9, [x9] 28 | add x0, x0, x9 29 | ret 30 | 31 | arm64_test_beq: 32 | .global arm64_test_beq 33 | .type arm64_test_beq, %function 34 | adds x0, x0, 1 35 | beq 1f 36 | sub x0, x0, 2 37 | 1: 38 | ret 39 | 40 | arm64_test_bne: 41 | .global arm64_test_bne 42 | .type arm64_test_bne, %function 43 | adds x0, x0, 1 44 | bne 1f 45 | sub x0, x0, 2 46 | 1: 47 | ret 48 | 49 | 50 | arm64_test_cbnz: 51 | .global arm64_test_cbnz 52 | .type arm64_test_cbnz, %function 53 | cbnz x0, 1f 54 | add x0, x0, 2 55 | 1: 56 | sub x0, x0, 1 57 | ret 58 | 59 | arm64_test_cbz: 60 | .global arm64_test_cbz 61 | .type arm64_test_cbz, %function 62 | cbz x0, 1f 63 | add x0, x0, 2 64 | 1: 65 | sub x0, x0, 1 66 | ret 67 | 68 | arm64_test_ldr_w: 69 | .global arm64_test_ldr_w 70 | .type arm64_test_ldr_w, %function 71 | ldr w9, test_data 72 | add x0, x0, x9 73 | ret 74 | 75 | arm64_test_ldr_x: 76 | .global arm64_test_ldr_x 77 | .type arm64_test_ldr_x, %function 78 | ldr x9, test_data 79 | add x0, x0, x9 80 | ret 81 | 82 | arm64_test_ldr_s: 83 | .global arm64_test_ldr_s 84 | .type arm64_test_ldr_s, %function 85 | ldr s16, test_data 86 | mov w9, v16.s[0] 87 | add x0, x0, x9 88 | ret 89 | 90 | arm64_test_ldr_d: 91 | .global arm64_test_ldr_d 92 | .type arm64_test_ldr_d, %function 93 | ldr d16, test_data 94 | mov x9, v16.d[0] 95 | add x0, x0, x9 96 | ret 97 | 98 | arm64_test_ldr_q: 99 | .global arm64_test_ldr_q 100 | .type arm64_test_ldr_q, %function 101 | ldr q16, test_data 102 | mov x9, v16.d[0] 103 | add x0, x0, x9 104 | mov x9, v16.d[1] 105 | add x0, x0, x9 106 | ret 107 | 108 | arm64_test_prfm: 109 | .global arm64_test_prfm 110 | .type arm64_test_prfm, %function 111 | prfm pldl1keep, test_data 112 | ldr x9, test_data 113 | add x0, x0, x9 114 | ret 115 | 116 | arm64_test_ldrsw: 117 | .global arm64_test_ldrsw 118 | .type arm64_test_ldrsw, %function 119 | ldrsw x9, 1f 120 | add x0, x0, x9 121 | ret 122 | 123 | arm64_test_tbnz: 124 | .global arm64_test_tbnz 125 | .type arm64_test_tbnz, %function 126 | tbnz x0, 32, 1f 127 | add x0, x0, 2 128 | 1: 129 | sub x0, x0, 1 130 | ret 131 | 132 | arm64_test_tbz: 133 | .global arm64_test_tbz 134 | .type arm64_test_tbz, %function 135 | tbz x0, 32, 1f 136 | add x0, x0, 2 137 | 1: 138 | sub x0, x0, 1 139 | ret 140 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test_x86_64_gas.S: -------------------------------------------------------------------------------- 1 | .text 2 | 3 | #if defined(__MINGW32__) 4 | .def get_val_in_dll; .scl 2; .type 32; .endef 5 | #elif defined(__APPLE__) 6 | #define get_val_in_dll _get_val_in_dll 7 | #define call_get_val_in_dll _call_get_val_in_dll 8 | #define jump_get_val_in_dll _jump_get_val_in_dll 9 | #else 10 | #define get_val_in_dll get_val_in_dll@PLT 11 | #endif 12 | 13 | .p2align 4,,15 14 | .globl call_get_val_in_dll 15 | #if defined(__MINGW32__) 16 | .def call_get_val_in_dll; .scl 2; .type 32; .endef 17 | #elif !defined(__APPLE__) 18 | .type call_get_val_in_dll, @function 19 | #endif 20 | call_get_val_in_dll: 21 | call get_val_in_dll 22 | ret 23 | 24 | .p2align 4,,15 25 | .globl jump_get_val_in_dll 26 | #if defined(__MINGW32__) 27 | .def jump_get_val_in_dll; .scl 2; .type 32; .endef 28 | #elif !defined(__APPLE__) 29 | .type jump_get_val_in_dll, @function 30 | #endif 31 | jump_get_val_in_dll: 32 | jmp get_val_in_dll 33 | 34 | #if defined(__MINGW32__) 35 | .section .drectve 36 | .ascii " -export:\"jump_get_val_in_dll\"" 37 | .ascii " -export:\"call_get_val_in_dll\"" 38 | #endif 39 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test_x86_64_masm.asm: -------------------------------------------------------------------------------- 1 | EXTRN get_val_in_dll:PROC 2 | 3 | _TEXT SEGMENT 4 | 5 | call_get_val_in_dll PROC EXPORT 6 | sub rsp, 40 7 | call get_val_in_dll 8 | add rsp, 40 9 | ret 0 10 | call_get_val_in_dll ENDP 11 | 12 | jump_get_val_in_dll PROC EXPORT 13 | jmp get_val_in_dll 14 | jump_get_val_in_dll ENDP 15 | 16 | _TEXT ENDS 17 | 18 | END 19 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test_x86_gas.S: -------------------------------------------------------------------------------- 1 | .text 2 | 3 | #if defined(__MINGW32__) 4 | #define call_get_val_in_dll _call_get_val_in_dll 5 | #define jump_get_val_in_dll _jump_get_val_in_dll 6 | #define __get_val_in_dll _get_val_in_dll 7 | .def get_val_in_dll; .scl 2; .type 32; .endef 8 | #elif defined(__APPLE__) 9 | #define call_get_val_in_dll _call_get_val_in_dll 10 | #define jump_get_val_in_dll _jump_get_val_in_dll 11 | #define __get_val_in_dll _get_val_in_dll 12 | #else 13 | .type __get_val_in_dll, @function 14 | __get_val_in_dll: 15 | pushl %ebx 16 | call __x86.get_pc_thunk.bx 17 | addl $_GLOBAL_OFFSET_TABLE_, %ebx 18 | subl $8, %esp 19 | call get_val_in_dll@PLT 20 | addl $8, %esp 21 | popl %ebx 22 | ret 23 | 24 | // padding in order not to use 1-byte relative addressing jump in jump_get_val_in_dll 25 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 26 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 27 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 28 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 29 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 30 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 31 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 32 | .byte 0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90,0x90 33 | #endif 34 | 35 | .p2align 4,,15 36 | .globl call_get_val_in_dll 37 | #if defined(__MINGW32__) 38 | .def call_get_val_in_dll; .scl 2; .type 32; .endef 39 | #elif !defined(__APPLE__) 40 | .type call_get_val_in_dll, @function 41 | #endif 42 | call_get_val_in_dll: 43 | call __get_val_in_dll 44 | ret 45 | 46 | .p2align 4,,15 47 | .globl jump_get_val_in_dll 48 | #if defined(__MINGW32__) 49 | .def jump_get_val_in_dll; .scl 2; .type 32; .endef 50 | #elif !defined(__APPLE__) 51 | .type jump_get_val_in_dll, @function 52 | #endif 53 | jump_get_val_in_dll: 54 | jmp __get_val_in_dll 55 | 56 | #if defined(__MINGW32__) 57 | .section .drectve 58 | .ascii " -export:\"jump_get_val_in_dll\"" 59 | .ascii " -export:\"call_get_val_in_dll\"" 60 | #elif !defined(__APPLE__) 61 | .section .text.__x86.get_pc_thunk.bx,"axG",@progbits,__x86.get_pc_thunk.bx,comdat 62 | .globl __x86.get_pc_thunk.bx 63 | .hidden __x86.get_pc_thunk.bx 64 | .type __x86.get_pc_thunk.bx, @function 65 | __x86.get_pc_thunk.bx: 66 | movl (%esp), %ebx 67 | ret 68 | #endif 69 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/funchook/test/libfunchook_test_x86_masm.asm: -------------------------------------------------------------------------------- 1 | .686P 2 | .XMM 3 | include listing.inc 4 | .model flat 5 | 6 | INCLUDELIB MSVCRT 7 | INCLUDELIB OLDNAMES 8 | 9 | PUBLIC _call_get_val_in_dll 10 | PUBLIC _jump_get_val_in_dll 11 | EXTRN _get_val_in_dll:PROC 12 | 13 | _TEXT SEGMENT 14 | 15 | _call_get_val_in_dll PROC EXPORT 16 | call _get_val_in_dll 17 | ret 0 18 | _call_get_val_in_dll ENDP 19 | 20 | _jump_get_val_in_dll PROC EXPORT 21 | jmp _get_val_in_dll 22 | _jump_get_val_in_dll ENDP 23 | 24 | _TEXT ENDS 25 | 26 | END 27 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/include/logger.h: -------------------------------------------------------------------------------- 1 | #ifndef _LOGGER_H_ 2 | #define _LOGGER_H_ 3 | 4 | #define PY_SSIZE_T_CLEAN 5 | #include 6 | 7 | typedef enum log_level 8 | { 9 | LOG_INFO = 0, 10 | LOG_WARNING, 11 | LOG_ERROR, 12 | LOG_DEBUG, 13 | } log_level_t; 14 | 15 | #define log_info(...) log_message(LOG_INFO, __VA_ARGS__) 16 | #define log_warning(...) log_message(LOG_WARNING, __VA_ARGS__) 17 | #define log_error(...) log_message(LOG_ERROR, __VA_ARGS__) 18 | #define log_debug(...) log_message(LOG_DEBUG, __VA_ARGS__) 19 | 20 | void set_logger(PyObject *_logger); 21 | void teardown_logger(void); 22 | void log_message(log_level_t level, const char *msg, ...); 23 | 24 | #endif /* _LOGGER_H_ */ 25 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/include/patch.h: -------------------------------------------------------------------------------- 1 | #ifndef _PATCH_H_ 2 | #define _PATCH_H_ 3 | 4 | #define PY_SSIZE_T_CLEAN 5 | #include 6 | 7 | #include 8 | #include 9 | 10 | int init_patch(void); 11 | void teardown_patch(void); 12 | 13 | PyObject *initialize(PyObject *self, PyObject *args); 14 | PyObject *enable_patches(PyObject *self, PyObject *arg); 15 | PyObject *install(PyObject *self, PyObject *arg); 16 | 17 | void patch_string_callback(char *prop_method_name, PyObject *source, PyObject *target, PyObject *hook_args, PyObject *hook_kwargs); 18 | 19 | PyObject *str_origin(PyObject *self, PyObject *args); 20 | 21 | int apply_cformat_patch(funchook_t *funchook); 22 | int apply_fstring_patch(funchook_t *funchook); 23 | int apply_cast_patch(funchook_t *funchook); 24 | int apply_concat_patch(funchook_t *funchook); 25 | 26 | #define BUILD_NEW_BINARYFUNC(NAME) \ 27 | static PyObject *NAME##_new(PyObject *self, PyObject *args) { \ 28 | PyObject *result = NAME##_origin(self, args); \ 29 | \ 30 | if (result == NULL) \ 31 | return result; \ 32 | \ 33 | patch_string_callback("callback_" #NAME, self, result, args, NULL); \ 34 | \ 35 | return result; \ 36 | } 37 | 38 | #endif /* _PATCH_H_ */ 39 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/include/utils.h: -------------------------------------------------------------------------------- 1 | #ifndef _UTILS_H_ 2 | #define _UTILS_H_ 3 | 4 | #define PY_SSIZE_T_CLEAN 5 | #include 6 | #include 7 | 8 | #include 9 | #include 10 | 11 | static inline PyObject *process_args(PyObject *const *args, Py_ssize_t args_size) { 12 | PyObject *hook_args = PyList_New(0); 13 | Py_ssize_t i; 14 | 15 | for (i = 0; i < args_size; i++) { 16 | PyList_Append(hook_args, args[i]); 17 | } 18 | 19 | return hook_args; 20 | } 21 | 22 | static inline bool need_to_pack(PyObject *obj) { 23 | return (!PySequence_Check(obj) || PyBytes_Check(obj) || PyUnicode_Check(obj) || PyByteArray_Check(obj)); 24 | } 25 | 26 | #define UNPACK_FUNCHOOK_CAPSULE \ 27 | do { \ 28 | if (!PyCapsule_IsValid(arg, NULL)) { \ 29 | log_error("Expected funchook container"); \ 30 | return NULL; \ 31 | } \ 32 | \ 33 | if ((funchook = (funchook_t *)PyCapsule_GetPointer(arg, NULL)) == NULL) { \ 34 | log_error( "Failed to get funchook from container"); \ 35 | return NULL; \ 36 | } \ 37 | } while (0); 38 | 39 | #define _funchook_prepare_wrapper(fh, origin_func, new_func, ret_val) \ 40 | do { \ 41 | if (funchook_prepare((fh), (void **)(origin_func), (new_func)) != \ 42 | FUNCHOOK_ERROR_SUCCESS) { \ 43 | PyErr_Format( \ 44 | PyExc_RuntimeError, \ 45 | "Failed to prepare hook at %s:%d: %s", \ 46 | __FILE__, \ 47 | __LINE__, \ 48 | funchook_error_message(fh)); \ 49 | return ret_val; \ 50 | } \ 51 | } while (0) 52 | 53 | #define funchook_prepare_wrapper(fh, origin_func, new_func) _funchook_prepare_wrapper(fh, origin_func, new_func, -1) 54 | 55 | #endif /* _UTILS_H_ */ 56 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/logger.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | static PyObject *logger = NULL; 11 | static const char *log_level_map[] = { 12 | "info", 13 | "warning", 14 | "error", 15 | "debug", 16 | }; 17 | 18 | void set_logger(PyObject *_logger) { 19 | Py_XINCREF(_logger); 20 | logger = _logger; 21 | } 22 | 23 | void teardown_logger() { 24 | Py_XDECREF(logger); 25 | logger = NULL; 26 | } 27 | 28 | void log_message(log_level_t level, const char *msg, ...) { 29 | PyObject *string = NULL; 30 | PyObject *result = NULL; 31 | va_list arg_p; 32 | 33 | if (logger == NULL) { 34 | return; 35 | } 36 | 37 | va_start(arg_p, msg); 38 | string = PyUnicode_FromFormatV(msg, arg_p); 39 | va_end(arg_p); 40 | 41 | if (string == NULL) { 42 | fprintf(stderr, "Failed to format log message\n"); 43 | return; 44 | } 45 | 46 | result = PyObject_CallMethod(logger, (char *)log_level_map[level], "O", string); 47 | if (result == NULL) { 48 | fprintf(stderr, "Failed to call log method\n"); 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/patch.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #define PATCH_MODULE_NAME "dongtai_agent_python.assess.c_api_hook" 10 | 11 | static PyObject *patch_module = NULL; 12 | 13 | int init_patch() { 14 | if (patch_module != NULL) { 15 | log_error("%s module already initialized", PATCH_MODULE_NAME); 16 | return -1; 17 | } 18 | 19 | patch_module = PyImport_ImportModule(PATCH_MODULE_NAME); 20 | if (patch_module == NULL) { 21 | log_error("Failed to import %s", PATCH_MODULE_NAME); 22 | return -1; 23 | } 24 | 25 | return 0; 26 | } 27 | 28 | #define apply_patch(apply_func, hook) \ 29 | do { \ 30 | if ((apply_func)((hook)) != 0) { \ 31 | teardown_patch(); \ 32 | funchook_destroy((hook)); \ 33 | return NULL; \ 34 | } \ 35 | } while (0); 36 | 37 | void teardown_patch() { 38 | Py_XDECREF(patch_module); 39 | patch_module = NULL; 40 | } 41 | 42 | PyObject *initialize(PyObject *self, PyObject *args) { 43 | PyObject *_log; 44 | if (!PyArg_ParseTuple(args, "O", &_log)) { 45 | return NULL; 46 | } 47 | set_logger(_log); 48 | 49 | if (init_patch() != 0) { 50 | return NULL; 51 | } 52 | 53 | funchook_t *funchook = NULL; 54 | if ((funchook = funchook_create()) == NULL) { 55 | log_error("Failed to create funchook object"); 56 | return NULL; 57 | } 58 | 59 | log_debug("Initialized C API patch"); 60 | 61 | return PyCapsule_New((void *)funchook, NULL, NULL); 62 | } 63 | 64 | PyObject *enable_patches(PyObject *self, PyObject *arg) { 65 | funchook_t *funchook = NULL; 66 | 67 | UNPACK_FUNCHOOK_CAPSULE; 68 | 69 | apply_patch(apply_cformat_patch, funchook); 70 | apply_patch(apply_fstring_patch, funchook); 71 | apply_patch(apply_cast_patch, funchook); 72 | apply_patch(apply_concat_patch, funchook); 73 | 74 | Py_RETURN_NONE; 75 | } 76 | 77 | PyObject *install(PyObject *self, PyObject *arg) { 78 | funchook_t *funchook = NULL; 79 | 80 | UNPACK_FUNCHOOK_CAPSULE; 81 | 82 | if (funchook_install(funchook, 0) != FUNCHOOK_ERROR_SUCCESS) { 83 | log_error("Failed to install C API patch: %s", funchook_error_message(funchook)); 84 | funchook_destroy(funchook); 85 | return NULL; 86 | } 87 | 88 | log_debug("Installed C API patch"); 89 | 90 | Py_RETURN_NONE; 91 | } 92 | 93 | void patch_string_callback(char *prop_method_name, PyObject *source, PyObject *target, PyObject *hook_args, PyObject *hook_kwargs) { 94 | if (!PyObject_HasAttrString(patch_module, prop_method_name)) { 95 | return; 96 | } 97 | 98 | PyObject *result; 99 | PyObject *prop_hook_args; 100 | int free_hook_args = 0; 101 | 102 | if (hook_args == NULL) { 103 | prop_hook_args = Py_None; 104 | } else if (need_to_pack(hook_args)) { 105 | prop_hook_args = PyTuple_Pack(1, hook_args); 106 | free_hook_args = 1; 107 | } else { 108 | prop_hook_args = hook_args; 109 | } 110 | 111 | result = PyObject_CallMethod( 112 | patch_module, 113 | prop_method_name, 114 | "OOOOO", 115 | target, /* target */ 116 | (source == NULL ? Py_None : source), /* self_obj */ 117 | target, /* ret */ 118 | prop_hook_args, /* args */ 119 | (hook_kwargs == NULL ? Py_None : hook_kwargs)); /* kwargs */ 120 | 121 | if (result == NULL) { 122 | PyErr_PrintEx(0); 123 | log_error("String method callback failed: %s", prop_method_name); 124 | } 125 | 126 | Py_XDECREF(result); 127 | if (free_hook_args) { 128 | Py_XDECREF(prop_hook_args); 129 | } 130 | } 131 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/patch/cast.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | 10 | #define IS_TRACKABLE(X) \ 11 | (PyUnicode_Check((X)) || PyBytes_Check((X)) || PyByteArray_Check((X))) 12 | 13 | newfunc bytes_cast_origin; 14 | initproc bytearray_cast_origin; 15 | newfunc unicode_cast_origin; 16 | 17 | PyObject *bytes_cast_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { 18 | PyObject *result = bytes_cast_origin(type, args, kwargs); 19 | 20 | if (result == NULL) { 21 | return result; 22 | } 23 | 24 | patch_string_callback("callback_bytes_cast", NULL, result, args, kwargs); 25 | 26 | return result; 27 | } 28 | 29 | int bytearray_cast_new(PyObject *self, PyObject *args, PyObject *kwargs) { 30 | int result = bytearray_cast_origin(self, args, kwargs); 31 | 32 | if (result == -1) { 33 | return result; 34 | } 35 | 36 | patch_string_callback("callback_bytearray_cast", NULL, self, args, kwargs); 37 | 38 | return result; 39 | } 40 | 41 | PyObject *str_origin(PyObject *self, PyObject *args) { 42 | return unicode_cast_origin(&PyUnicode_Type, args, NULL); 43 | } 44 | 45 | PyObject *unicode_cast_new(PyTypeObject *type, PyObject *args, PyObject *kwargs) { 46 | PyObject *result = unicode_cast_origin(type, args, kwargs); 47 | 48 | if (result == NULL) { 49 | return result; 50 | } 51 | 52 | patch_string_callback("callback_unicode_cast", NULL, result, args, kwargs); 53 | 54 | return result; 55 | } 56 | 57 | int apply_cast_patch(funchook_t *funchook) { 58 | bytes_cast_origin = (void *)PyBytes_Type.tp_new; 59 | funchook_prepare_wrapper(funchook, (PyCFunction)&bytes_cast_origin, bytes_cast_new); 60 | 61 | bytearray_cast_origin = (void *)PyByteArray_Type.tp_init; 62 | funchook_prepare_wrapper(funchook, (PyCFunction)&bytearray_cast_origin, bytearray_cast_new); 63 | 64 | unicode_cast_origin = (void *)PyUnicode_Type.tp_new; 65 | funchook_prepare_wrapper(funchook, (PyCFunction)&unicode_cast_origin, unicode_cast_new); 66 | 67 | log_debug("------c_patch------------------ cast"); 68 | 69 | return 0; 70 | } 71 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/patch/concat.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | binaryfunc bytes_concat_origin; 10 | binaryfunc bytearray_concat_origin; 11 | binaryfunc bytearray_inplace_concat_origin; 12 | binaryfunc unicode_concat_origin; 13 | void (*unicode_append_origin)(PyObject **l, PyObject *r); 14 | 15 | PyObject *bytes_concat_new(PyObject *l, PyObject *r) { 16 | PyObject *result = bytes_concat_origin(l, r); 17 | 18 | if (result == NULL) { 19 | return result; 20 | } 21 | 22 | patch_string_callback("callback_bytes_concat", l, result, r, NULL); 23 | 24 | return result; 25 | } 26 | 27 | PyObject *bytearray_concat_new(PyObject *l, PyObject *r) { 28 | PyObject *result = bytearray_concat_origin(l, r); 29 | 30 | if (result == NULL) { 31 | return result; 32 | } 33 | 34 | patch_string_callback("callback_bytearray_concat", l, result, r, NULL); 35 | 36 | return result; 37 | } 38 | 39 | PyObject *bytearray_inplace_concat_new(PyObject *l, PyObject *r) { 40 | PyObject *result = bytearray_inplace_concat_origin(l, r); 41 | 42 | if (result == NULL) { 43 | return result; 44 | } 45 | 46 | patch_string_callback("callback_bytearray_concat", l, result, r, NULL); 47 | 48 | return result; 49 | } 50 | 51 | PyObject *unicode_concat_new(PyObject *l, PyObject *r) { 52 | PyObject *result = unicode_concat_origin(l, r); 53 | 54 | if (result == NULL) { 55 | return result; 56 | } 57 | 58 | patch_string_callback("callback_unicode_concat", l, result, r, NULL); 59 | 60 | return result; 61 | } 62 | 63 | void unicode_append_new(PyObject **l, PyObject *r) { 64 | PyObject *origin_l = *l; 65 | Py_XINCREF(origin_l); 66 | unicode_append_origin(l, r); 67 | 68 | if (*l == NULL) { 69 | Py_XDECREF(origin_l); 70 | return; 71 | } 72 | 73 | patch_string_callback("callback_unicode_concat", origin_l, *l, r, NULL); 74 | Py_XDECREF(origin_l); 75 | } 76 | 77 | int apply_concat_patch(funchook_t *funchook) { 78 | bytes_concat_origin = PyBytes_Type.tp_as_sequence->sq_concat; 79 | funchook_prepare_wrapper(funchook, &bytes_concat_origin, bytes_concat_new); 80 | 81 | bytearray_concat_origin = PyByteArray_Concat; 82 | funchook_prepare_wrapper(funchook, &bytearray_concat_origin, bytearray_concat_new); 83 | 84 | bytearray_inplace_concat_origin = PyByteArray_Type.tp_as_sequence->sq_inplace_concat; 85 | funchook_prepare_wrapper(funchook, &bytearray_inplace_concat_origin, bytearray_inplace_concat_new); 86 | 87 | unicode_concat_origin = PyUnicode_Concat; 88 | funchook_prepare_wrapper(funchook, &unicode_concat_origin, unicode_concat_new); 89 | 90 | unicode_append_origin = PyUnicode_Append; 91 | funchook_prepare_wrapper(funchook, &unicode_append_origin, unicode_append_new); 92 | 93 | log_debug("------c_patch------------------ concat"); 94 | 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/patch/str_cformat.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | static binaryfunc bytes_cformat_origin; 10 | static binaryfunc bytearray_cformat_origin; 11 | static binaryfunc unicode_cformat_origin; 12 | 13 | BUILD_NEW_BINARYFUNC(bytes_cformat); 14 | BUILD_NEW_BINARYFUNC(bytearray_cformat); 15 | BUILD_NEW_BINARYFUNC(unicode_cformat); 16 | 17 | int apply_cformat_patch(funchook_t *funchook) { 18 | bytes_cformat_origin = PyBytes_Type.tp_as_number->nb_remainder; 19 | funchook_prepare_wrapper(funchook, &bytes_cformat_origin, bytes_cformat_new); 20 | 21 | bytearray_cformat_origin = PyByteArray_Type.tp_as_number->nb_remainder; 22 | funchook_prepare_wrapper(funchook, &bytearray_cformat_origin, bytearray_cformat_new); 23 | 24 | unicode_cformat_origin = PyUnicode_Format; 25 | funchook_prepare_wrapper(funchook, &unicode_cformat_origin, unicode_cformat_new); 26 | 27 | log_debug("------c_patch------------------ cformat"); 28 | 29 | return 0; 30 | } 31 | -------------------------------------------------------------------------------- /dongtai_agent_python/assess_ext/patch/str_fstring.c: -------------------------------------------------------------------------------- 1 | #define PY_SSIZE_T_CLEAN 2 | #include 3 | 4 | #include 5 | #include 6 | #include 7 | #include 8 | 9 | #if PY_MINOR_VERSION == 6 10 | typedef PyObject **joinarray_items_t; 11 | #else 12 | typedef PyObject *const *joinarray_items_t; 13 | #endif /* PY_MINOR_VERSION == 6 */ 14 | 15 | PyObject *(*unicode_joinarray_origin)(PyObject *, joinarray_items_t, Py_ssize_t); 16 | 17 | static PyObject *unicode_joinarray_new(PyObject *sep, joinarray_items_t items, Py_ssize_t len) { 18 | PyObject *result = unicode_joinarray_origin(sep, items, len); 19 | 20 | if (result == NULL || len == 0) { 21 | return result; 22 | } 23 | 24 | PyObject *args = process_args(items, len); 25 | 26 | patch_string_callback("callback_unicode_fstring", sep, result, args, NULL); 27 | 28 | Py_XDECREF(args); 29 | return result; 30 | } 31 | 32 | int apply_fstring_patch(funchook_t *funchook) { 33 | unicode_joinarray_origin = _PyUnicode_JoinArray; 34 | funchook_prepare_wrapper(funchook, &unicode_joinarray_origin, unicode_joinarray_new); 35 | log_debug("------c_patch------------------ fstring"); 36 | 37 | return 0; 38 | } 39 | -------------------------------------------------------------------------------- /dongtai_agent_python/cli/__init__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | 5 | _builtin_commands = [ 6 | 'run', 7 | ] 8 | 9 | _commands = {} 10 | 11 | 12 | def command(name, options='', description='', hidden=False, 13 | log_intercept=True, deprecated=False): 14 | def wrapper(callback): 15 | callback.name = name 16 | callback.options = options 17 | callback.description = description 18 | callback.hidden = hidden 19 | callback.log_intercept = log_intercept 20 | callback.deprecated = deprecated 21 | _commands[name] = callback 22 | return callback 23 | 24 | return wrapper 25 | 26 | 27 | def usage(name): 28 | cmd = _commands[name] 29 | if cmd.deprecated: 30 | print("Command %s is deprecated" % (name,)) 31 | print('Usage: dongtai-cli %s %s' % (name, cmd.options)) 32 | 33 | 34 | def log_message(text): 35 | timestamp = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) 36 | print('[%s] [%d] DongTai: %s' % (timestamp, os.getpid(), text)) 37 | 38 | 39 | def load_internal_commands(): 40 | for name in _builtin_commands: 41 | module_name = '%s.%s' % (__name__, name) 42 | __import__(module_name) 43 | 44 | 45 | def main(): 46 | if len(sys.argv) > 1: 47 | cmd = sys.argv[1] 48 | else: 49 | print("Command can not empty") 50 | sys.exit(1) 51 | 52 | try: 53 | callback = _commands[cmd] 54 | except Exception: 55 | print("Unknown command " + cmd) 56 | sys.exit(1) 57 | 58 | callback(sys.argv[2:]) 59 | 60 | 61 | load_internal_commands() 62 | 63 | if __name__ == '__main__': 64 | main() 65 | -------------------------------------------------------------------------------- /dongtai_agent_python/common/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from dongtai_agent_python.setting import Setting 3 | from dongtai_agent_python.utils import scope 4 | 5 | loggers = {} 6 | 7 | LOG_FORMAT = '[%(asctime)s] %(levelname)s [%(name)s] %(message)s' # 每条日志输出格式 8 | 9 | 10 | class AgentLogger(object): 11 | def __init__(self, log): 12 | self._log = log 13 | 14 | @scope.with_scope(scope.SCOPE_AGENT) 15 | def debug(self, msg, *args, **kwargs): 16 | return self._log.debug(msg, *args, **kwargs) 17 | 18 | @scope.with_scope(scope.SCOPE_AGENT) 19 | def info(self, msg, *args, **kwargs): 20 | return self._log.info(msg, *args, **kwargs) 21 | 22 | @scope.with_scope(scope.SCOPE_AGENT) 23 | def warning(self, msg, *args, **kwargs): 24 | return self._log.warning(msg, *args, **kwargs) 25 | 26 | @scope.with_scope(scope.SCOPE_AGENT) 27 | def warn(self, msg, *args, **kwargs): 28 | return self._log.warn(msg, *args, **kwargs) 29 | 30 | @scope.with_scope(scope.SCOPE_AGENT) 31 | def error(self, msg, *args, **kwargs): 32 | return self._log.error(msg, *args, **kwargs) 33 | 34 | @scope.with_scope(scope.SCOPE_AGENT) 35 | def exception(self, msg, *args, exc_info=True, **kwargs): 36 | return self._log.exception(msg, *args, exc_info, **kwargs) 37 | 38 | @scope.with_scope(scope.SCOPE_AGENT) 39 | def critical(self, msg, *args, **kwargs): 40 | return self._log.critical(msg, *args, **kwargs) 41 | 42 | @scope.with_scope(scope.SCOPE_AGENT) 43 | def log(self, level, msg, *args, **kwargs): 44 | return self._log.log(level, msg, *args, **kwargs) 45 | 46 | 47 | @scope.with_scope(scope.SCOPE_AGENT) 48 | def logger_config(logging_name): 49 | """ 50 | get logger by name 51 | :param logging_name: name of logger 52 | :return: logger 53 | """ 54 | 55 | global loggers 56 | 57 | if loggers.get(logging_name): 58 | return loggers.get(logging_name) 59 | 60 | # get config 61 | setting = Setting() 62 | log_path = setting.log_path 63 | 64 | logger = logging.getLogger(logging_name) 65 | logger.handlers.clear() 66 | 67 | if setting.debug: 68 | level = logging.DEBUG 69 | else: 70 | level = logging.INFO 71 | 72 | logger.setLevel(level) 73 | 74 | handler = logging.FileHandler(log_path, encoding='UTF-8') 75 | handler.setLevel(level) 76 | handler.setFormatter(logging.Formatter(LOG_FORMAT)) 77 | logger.addHandler(handler) 78 | 79 | console = logging.StreamHandler() 80 | console.setLevel(level) 81 | console.setFormatter(logging.Formatter(LOG_FORMAT)) 82 | logger.addHandler(console) 83 | 84 | loggers[logging_name] = logger 85 | return AgentLogger(logger) 86 | -------------------------------------------------------------------------------- /dongtai_agent_python/config-example.json: -------------------------------------------------------------------------------- 1 | { 2 | "debug": false, 3 | "iast": { 4 | "proxy": { 5 | "port": 80, 6 | "host": "", 7 | "enable": false 8 | }, 9 | "server": { 10 | "mode": "remote", 11 | "token": "42662f1c621ec6b99b52b98b4fea81a70b11a59a", 12 | "url": "http://192.168.2.133:8002" 13 | }, 14 | "service": { 15 | "report": { 16 | "interval": 5 17 | }, 18 | "replay": { 19 | "interval": 300 20 | } 21 | }, 22 | "dump": { 23 | "class": { 24 | "enable": false, 25 | "path": "./iast-class-dump/" 26 | } 27 | }, 28 | "engine": { 29 | "delay": { 30 | "time": 10 31 | } 32 | }, 33 | "allhook": { 34 | "enable": true 35 | }, 36 | "name": "DongTai", 37 | "mode": "normal" 38 | }, 39 | "project": { 40 | "name": "Python Demo Project", 41 | "version": "" 42 | }, 43 | "engine": { 44 | "version": "v1.3.0", 45 | "name": "dongtai-agent-python" 46 | }, 47 | "app": { 48 | "name": "DongTai" 49 | }, 50 | "log": { 51 | "log_path": "./dongtai_py_agent.log" 52 | } 53 | } -------------------------------------------------------------------------------- /dongtai_agent_python/context/__init__.py: -------------------------------------------------------------------------------- 1 | from .request_context import RequestContext 2 | from .tracker import ContextTracker 3 | from .request import DjangoRequest, FlaskRequest 4 | -------------------------------------------------------------------------------- /dongtai_agent_python/context/request.py: -------------------------------------------------------------------------------- 1 | import json 2 | from io import BytesIO 3 | 4 | from dongtai_agent_python.utils import scope 5 | 6 | 7 | class Request(object): 8 | def __init__(self, request): 9 | super(Request, self).__init__() 10 | 11 | self.scheme = request.scheme 12 | self.headers = dict(request.headers) 13 | 14 | 15 | class DjangoRequest(Request): 16 | def __init__(self, request): 17 | super(DjangoRequest, self).__init__(request) 18 | 19 | self.environ = request.META 20 | self.url = self.scheme + "://" + self.environ.get("HTTP_HOST", "") + self.environ.get("PATH_INFO", "") 21 | if self.environ.get("QUERY_STRING", ""): 22 | self.url += "?" + self.environ.get("QUERY_STRING", "") 23 | 24 | self.body = self.get_request_body(request) 25 | 26 | @scope.with_scope(scope.SCOPE_AGENT) 27 | def get_request_body(self, request): 28 | request_body = "" 29 | if request.POST: 30 | forms = [] 31 | for key in request.POST: 32 | forms.append(key + "=" + request.POST[key]) 33 | request_body = "&".join(forms) 34 | if request_body == "": 35 | try: 36 | req_body = request.META['wsgi.input'].read() 37 | request._stream.stream = BytesIO(req_body) 38 | if req_body and isinstance(req_body, bytes): 39 | request_body = bytes.decode(req_body, "utf-8", errors="ignore") 40 | except Exception: 41 | pass 42 | 43 | return request_body 44 | 45 | 46 | class FlaskRequest(Request): 47 | def __init__(self, request): 48 | super(FlaskRequest, self).__init__(request) 49 | 50 | self.environ = request.environ 51 | self.url = self.scheme + "://" + self.environ.get("HTTP_HOST", "") + self.environ.get("PATH_INFO", "") 52 | if self.environ.get("QUERY_STRING", ""): 53 | self.url += "?" + self.environ.get("QUERY_STRING", "") 54 | self.body = self.get_request_body(request) 55 | 56 | @scope.with_scope(scope.SCOPE_AGENT) 57 | def get_request_body(self, request): 58 | request_body = "" 59 | if request.is_json and request.json: 60 | request_body = json.dumps(request.json) 61 | elif request.form: 62 | forms = [] 63 | for key in request.form: 64 | forms.append(key + "=" + request.form[key]) 65 | request_body = "&".join(forms) 66 | elif request.get_data(): 67 | request_body = bytes.decode(request.get_data(), "utf-8", errors="ignore") 68 | 69 | return request_body 70 | -------------------------------------------------------------------------------- /dongtai_agent_python/context/request_context.py: -------------------------------------------------------------------------------- 1 | from http.client import responses 2 | 3 | from dongtai_agent_python.utils import utils 4 | from dongtai_agent_python.common.logger import logger_config 5 | from dongtai_agent_python.setting import Setting 6 | from dongtai_agent_python.utils import scope 7 | 8 | logger = logger_config("request_context") 9 | 10 | 11 | class RequestContext(object): 12 | def __init__(self, request): 13 | self.has_source = False 14 | self.taint_ids = [] 15 | self.pool = [] 16 | self.tags = {} 17 | 18 | self.setting = Setting() 19 | self.setting.incr_request_seq() 20 | self.request = request 21 | 22 | self.detail = { 23 | "language": "PYTHON", 24 | "replayRequest": False, 25 | "agentId": self.setting.agent_id, 26 | "uri": request.environ.get("PATH_INFO", "/"), 27 | "url": request.url, 28 | "queryString": request.environ.get("QUERY_STRING", ""), 29 | "protocol": request.environ.get("SERVER_PROTOCOL", "'HTTP/1.1'"), 30 | "contextPath": request.environ.get("PATH_INFO", "/"), 31 | "clientIp": request.environ.get("REMOTE_ADDR", "127.0.0.1"), 32 | "method": request.environ.get("REQUEST_METHOD", "None"), 33 | "reqHeader": utils.json_to_base64(request.headers), 34 | "reqBody": request.body, 35 | "scheme": request.scheme, 36 | } 37 | 38 | logger.info("hook request success") 39 | 40 | @scope.with_scope(scope.SCOPE_AGENT) 41 | def extract_response(self, header, status_code, body): 42 | protocol = self.request.environ.get("SERVER_PROTOCOL", "'HTTP/1.1'") 43 | status_line = protocol + " " + str(status_code) + " " + responses[status_code] 44 | header['agentId'] = self.setting.agent_id 45 | 46 | res_header = utils.normalize_response_header(status_line, header) 47 | self.detail['resHeader'] = res_header 48 | self.detail['resBody'] = body 49 | 50 | logger.info("hook response success") 51 | -------------------------------------------------------------------------------- /dongtai_agent_python/context/tracker.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from collections import defaultdict 3 | from contextlib import contextmanager 4 | 5 | 6 | class ContextTracker(object): 7 | CURRENT_CONTEXT = "CURRENT_CONTEXT" 8 | 9 | def __init__(self): 10 | self._tracker = defaultdict(dict) 11 | 12 | def get(self, key, default=None): 13 | cid = self.current_thread_id() 14 | if cid == 0 or cid not in self._tracker or key not in self._tracker[cid]: 15 | return default 16 | 17 | return self._tracker[cid][key] 18 | 19 | def clear(self): 20 | self._tracker.clear() 21 | 22 | def set(self, key, value): 23 | cid = self.current_thread_id() 24 | if cid == 0: 25 | return 26 | self._tracker[cid][key] = value 27 | 28 | def delete(self, key): 29 | cid = self.current_thread_id() 30 | 31 | if cid not in self._tracker or key not in self._tracker[cid]: 32 | return 33 | 34 | del self._tracker[cid][key] 35 | 36 | if len(self._tracker[cid]) == 0: 37 | del self._tracker[cid] 38 | 39 | def set_current(self, value): 40 | self.set(self.CURRENT_CONTEXT, value) 41 | 42 | def delete_current(self): 43 | self.delete(self.CURRENT_CONTEXT) 44 | 45 | @contextmanager 46 | def lifespan(self, context): 47 | self.set_current(context) 48 | 49 | yield context 50 | 51 | self.delete_current() 52 | 53 | def current(self): 54 | return self.get(self.CURRENT_CONTEXT) 55 | 56 | def current_thread_id(self): 57 | tid = threading.get_ident() 58 | if tid not in threading._active: 59 | return 0 60 | return tid 61 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_middleware import BaseMiddleware 2 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/base_middleware.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | import time 4 | from concurrent.futures import ThreadPoolExecutor 5 | 6 | from dongtai_agent_python.api import OpenAPI 7 | from dongtai_agent_python.assess.patch import enable_patches 8 | from dongtai_agent_python.common.logger import logger_config 9 | from dongtai_agent_python.setting import Setting 10 | from dongtai_agent_python.utils import scope 11 | 12 | logger = logger_config("base_middleware") 13 | 14 | 15 | class BaseMiddleware(object): 16 | loaded = False 17 | 18 | def __init__(self, container): 19 | if BaseMiddleware.loaded: 20 | return 21 | 22 | start_time = time.time() 23 | scope.enter_scope(scope.SCOPE_AGENT) 24 | 25 | self.init_setting() 26 | logger.info("python agent init, version: " + self.setting.version) 27 | 28 | self.setting.set_container(container) 29 | 30 | # middleware id 31 | self.id = id(self) 32 | self.executor = ThreadPoolExecutor() 33 | 34 | self.openapi = OpenAPI(self.setting) 35 | 36 | # register agent 37 | register_resp = self.openapi.agent_register() 38 | if register_resp.get("status", 0) == 201: 39 | logger.info("python agent register success ") 40 | else: 41 | logger.error("python agent register error ") 42 | 43 | logger.debug("------begin hook-----") 44 | policies = self.get_policies() 45 | enable_patches(policies) 46 | 47 | self.openapi.agent_startup_time((time.time() - start_time) * 1000) 48 | logger.info("python agent hook open") 49 | 50 | scope.exit_scope() 51 | BaseMiddleware.loaded = True 52 | 53 | def init_setting(self): 54 | self.setting = Setting() 55 | 56 | def get_policies(self): 57 | if self.setting.use_local_policy: 58 | base_dir = os.path.dirname(os.path.abspath(__file__)) 59 | file_path = os.path.join(base_dir, '../policy_api.json') 60 | with open(file_path, 'r') as f: 61 | policies = json.load(f) 62 | else: 63 | policies = self.openapi.get_policies() 64 | 65 | if policies.get("status", 0) != 201: 66 | return [] 67 | return policies.get('data', []) 68 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/django_middleware.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | import django 4 | 5 | from dongtai_agent_python import CONTEXT_TRACKER 6 | from dongtai_agent_python.common.logger import logger_config 7 | from dongtai_agent_python.context import RequestContext, DjangoRequest 8 | from dongtai_agent_python.middlewares.base_middleware import BaseMiddleware 9 | from dongtai_agent_python.utils import scope 10 | from dongtai_agent_python.setting import const 11 | 12 | logger = logger_config("python_agent") 13 | 14 | 15 | class FireMiddleware(BaseMiddleware): 16 | def __init__(self, get_response=None): 17 | self.get_response = get_response 18 | 19 | super(FireMiddleware, self).__init__({ 20 | "name": const.CONTAINER_DJANGO, 21 | "version": django.get_version() 22 | }) 23 | 24 | def __call__(self, request): 25 | # agent paused 26 | if self.setting.is_agent_paused(): 27 | return self.get_response(request) 28 | 29 | context = RequestContext(DjangoRequest(request)) 30 | with CONTEXT_TRACKER.lifespan(context): 31 | return self.process_response(context, request) 32 | 33 | def process_response(self, context, request): 34 | response = self.get_response(request) 35 | 36 | self.process_response_data(context, response) 37 | 38 | context = CONTEXT_TRACKER.current() 39 | context.detail['pool'] = context.pool 40 | self.openapi.async_report_upload(self.executor, context.detail) 41 | 42 | return response 43 | 44 | @scope.with_scope(scope.SCOPE_AGENT) 45 | def process_response_data(self, context, response): 46 | if not response.streaming and response.content and isinstance(response.content, bytes): 47 | http_res_body = base64.b64encode(response.content).decode('utf-8') 48 | else: 49 | http_res_body = "" 50 | 51 | if hasattr(response, 'headers'): 52 | # django >= 3.2 53 | # https://docs.djangoproject.com/en/3.2/releases/3.2/#requests-and -responses 54 | resp_header = dict(response.headers) 55 | else: 56 | # django < 3.2 57 | resp_header = dict( 58 | (key, value) for key, value in response._headers.values() 59 | ) 60 | 61 | context.extract_response(resp_header, response.status_code, http_res_body) 62 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/django_wsgi_middleware.py: -------------------------------------------------------------------------------- 1 | import django 2 | 3 | from dongtai_agent_python.middlewares.wsgi_middleware import WSGIMiddleware 4 | from dongtai_agent_python.setting import const 5 | 6 | 7 | class DjangoWSGIMiddleware(WSGIMiddleware): 8 | def __init__(self, wsgi_app): 9 | super(DjangoWSGIMiddleware, self).__init__(wsgi_app, { 10 | "name": const.CONTAINER_DJANGO, 11 | "version": django.get_version() 12 | }) 13 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/flask_middleware.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | import flask 4 | from flask import request 5 | 6 | from dongtai_agent_python import CONTEXT_TRACKER 7 | from dongtai_agent_python.common.logger import logger_config 8 | from dongtai_agent_python.context import RequestContext, FlaskRequest 9 | from dongtai_agent_python.middlewares.base_middleware import BaseMiddleware 10 | from dongtai_agent_python.utils import scope 11 | from dongtai_agent_python.setting import const 12 | 13 | logger = logger_config("python_agent") 14 | 15 | 16 | class AgentMiddleware(BaseMiddleware): 17 | def __init__(self, old_app, app): 18 | self.old_wsgi_app = old_app 19 | 20 | super(AgentMiddleware, self).__init__({ 21 | "name": const.CONTAINER_FLASK, 22 | "version": flask.__version__ 23 | }) 24 | 25 | @app.before_request 26 | def process_request_hook(*args, **kwargs): 27 | # agent paused 28 | if self.setting.is_agent_paused(): 29 | return 30 | 31 | context = RequestContext(FlaskRequest(request)) 32 | CONTEXT_TRACKER.set_current(context) 33 | 34 | @app.after_request 35 | def process_response_hook(response): 36 | if self.setting.is_agent_paused(): 37 | return response 38 | 39 | context = CONTEXT_TRACKER.current() 40 | 41 | process_response_data(context, response) 42 | 43 | context.detail['pool'] = context.pool 44 | self.openapi.async_report_upload(self.executor, context.detail) 45 | 46 | return response 47 | 48 | @scope.with_scope(scope.SCOPE_AGENT) 49 | def process_response_data(context, response): 50 | if not response.is_streamed and response.data and isinstance(response.data, bytes): 51 | http_res_body = base64.b64encode(response.data).decode('utf-8') 52 | else: 53 | http_res_body = "" 54 | 55 | resp_header = dict(response.headers) 56 | resp_header['agentId'] = self.setting.agent_id 57 | 58 | context.extract_response(resp_header, response.status_code, http_res_body) 59 | 60 | def __call__(self, *args, **kwargs): 61 | obj = self.old_wsgi_app(*args, **kwargs) 62 | CONTEXT_TRACKER.delete_current() 63 | return obj 64 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/flask_wsgi_middleware.py: -------------------------------------------------------------------------------- 1 | import flask 2 | 3 | from dongtai_agent_python.middlewares.wsgi_middleware import WSGIMiddleware 4 | from dongtai_agent_python.setting import const 5 | 6 | 7 | class FlaskWSGIMiddleware(WSGIMiddleware): 8 | def __init__(self, app): 9 | super(FlaskWSGIMiddleware, self).__init__(app.wsgi_app, { 10 | "name": const.CONTAINER_FLASK, 11 | "version": flask.__version__ 12 | }) 13 | -------------------------------------------------------------------------------- /dongtai_agent_python/middlewares/wsgi_middleware.py: -------------------------------------------------------------------------------- 1 | import base64 2 | from http.client import responses 3 | 4 | import webob 5 | 6 | from dongtai_agent_python import CONTEXT_TRACKER 7 | from dongtai_agent_python.common.logger import logger_config 8 | from dongtai_agent_python.middlewares import BaseMiddleware 9 | from dongtai_agent_python.setting import Setting 10 | from dongtai_agent_python.utils import scope, utils 11 | 12 | logger = logger_config("wsgi_middleware") 13 | 14 | 15 | class WSGIRequest(webob.BaseRequest): 16 | def __init__(self, environ): 17 | """ 18 | Django is not fully wsgi-compliant, so we need its request body to be passed in 19 | explicitly. 20 | """ 21 | super(WSGIRequest, self).__init__(environ) 22 | 23 | 24 | class WSGIRequestContext(object): 25 | def __init__(self, environ): 26 | scope.enter_scope(scope.SCOPE_AGENT) 27 | 28 | self.environ = environ 29 | self.request = WSGIRequest(environ) 30 | 31 | self.has_source = False 32 | self.taint_ids = [] 33 | self.pool = [] 34 | self.tags = {} 35 | 36 | self.setting = Setting() 37 | self.setting.incr_request_seq() 38 | 39 | req_header = {} 40 | for header_key, header_value in self.request.headers.items(): 41 | req_header[header_key] = header_value 42 | 43 | self.detail = { 44 | "language": "PYTHON", 45 | "replayRequest": False, 46 | "agentId": self.setting.agent_id, 47 | "uri": environ.get("PATH_INFO", "/"), 48 | "url": self.request.url, 49 | "queryString": environ.get("QUERY_STRING", ""), 50 | "protocol": environ.get("SERVER_PROTOCOL", "'HTTP/1.1'"), 51 | "contextPath": environ.get("PATH_INFO", "/"), 52 | "clientIp": environ.get("REMOTE_ADDR", "127.0.0.1"), 53 | "method": environ.get("REQUEST_METHOD", "None"), 54 | "reqHeader": utils.json_to_base64(req_header), 55 | "reqBody": self.request.body.decode('utf-8', errors='ignore'), 56 | "scheme": self.request.scheme, 57 | } 58 | 59 | logger.info("hook request success") 60 | scope.exit_scope() 61 | 62 | @scope.with_scope(scope.SCOPE_AGENT) 63 | def extract_response(self, response): 64 | protocol = self.environ.get("SERVER_PROTOCOL", "'HTTP/1.1'") 65 | status_line = protocol + " " + str(response.status_code) + " " + responses[response.status_code] 66 | 67 | res_header = {} 68 | for header_key, header_value in response.headers.items(): 69 | res_header[header_key] = header_value 70 | res_header['agentId'] = self.setting.agent_id 71 | 72 | self.detail['resHeader'] = utils.normalize_response_header(status_line, res_header) 73 | 74 | body = response.body 75 | res_body = '' 76 | if isinstance(body, (bytes, str)): 77 | res_body = base64.b64encode(body).decode('utf-8') 78 | self.detail['resBody'] = res_body 79 | 80 | logger.info("hook response success") 81 | 82 | 83 | class WSGIMiddleware(BaseMiddleware): 84 | def __init__(self, wsgi_app, container): 85 | self.wsgi_app = wsgi_app 86 | 87 | super(WSGIMiddleware, self).__init__(container) 88 | 89 | def __call__(self, environ, start_response): 90 | context = WSGIRequestContext(environ) 91 | with CONTEXT_TRACKER.lifespan(context): 92 | return self.process_response(context, environ, start_response) 93 | 94 | def process_response(self, context, environ, start_response): 95 | try: 96 | response = WSGIRequest(environ).get_response(self.wsgi_app) 97 | context.extract_response(response) 98 | 99 | return response(environ, start_response) 100 | finally: 101 | context.detail['pool'] = context.pool 102 | self.openapi.async_report_upload(self.executor, context.detail) 103 | -------------------------------------------------------------------------------- /dongtai_agent_python/policy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/policy/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/policy/deal_data.py: -------------------------------------------------------------------------------- 1 | from dongtai_agent_python import CONTEXT_TRACKER 2 | from dongtai_agent_python.policy.tracking import Tracking 3 | from dongtai_agent_python.setting import Setting, const 4 | from dongtai_agent_python.utils import scope, utils 5 | 6 | 7 | @scope.with_scope(scope.SCOPE_AGENT) 8 | def wrap_data(policy_rule, self_obj=None, result=None, come_args=None, come_kwargs=None): 9 | setting = Setting() 10 | if setting.is_agent_paused(): 11 | return 12 | 13 | context = CONTEXT_TRACKER.current() 14 | if not utils.needs_propagation(context, policy_rule.node_type): 15 | return 16 | 17 | if not filter_result(result, policy_rule.node_type): 18 | return 19 | 20 | if policy_rule.node_type == const.NODE_TYPE_SOURCE: 21 | context.has_source = True 22 | 23 | tracking = Tracking(policy_rule) 24 | tracking.apply(self_obj, result, come_args, come_kwargs) 25 | 26 | 27 | def filter_result(result, node_type=None): 28 | if node_type != const.NODE_TYPE_SINK: 29 | if utils.is_empty(result) or utils.is_not_allowed_type(result): 30 | return False 31 | 32 | return True 33 | -------------------------------------------------------------------------------- /dongtai_agent_python/policy/policy.py: -------------------------------------------------------------------------------- 1 | from dongtai_agent_python.setting import const 2 | 3 | 4 | def new_policy_rule(rule_type, detail): 5 | signature = detail.get('value', '') 6 | if signature == '' or len(signature.split("."))<2: 7 | return None 8 | if rule_type not in const.NODE_TYPES: 9 | return None 10 | return PolicyRule(rule_type, signature, detail.get('source', None), detail.get('target', None)) 11 | 12 | 13 | class PolicyRule(object): 14 | def __init__(self, node_type, signature, source=None, target=None): 15 | self.node_type = node_type 16 | self.signature = signature 17 | splits = signature.split(".") 18 | self.class_name = splits[-2] 19 | self.method_name = splits[-1] 20 | self.fully_class_name = signature[:-len(self.method_name) - 1] 21 | 22 | self.origin_method = None 23 | self.patched_method = None 24 | 25 | self.source_from = TaintFrom(const.TAINT_SOURCE, source) 26 | self.target_from = TaintFrom(const.TAINT_TARGET, target) 27 | 28 | def set_origin_method(self, origin_method): 29 | self.origin_method = origin_method 30 | 31 | def set_patched_method(self, patched_method): 32 | self.patched_method = patched_method 33 | 34 | def get_source_taints(self, self_obj, result, args, kwargs): 35 | return self.source_from.get_taints(self_obj, result, args, kwargs) 36 | 37 | def get_target_taints(self, self_obj, result, args, kwargs): 38 | return self.target_from.get_taints(self_obj, result, args, kwargs) 39 | 40 | 41 | class TaintFrom(object): 42 | def __init__(self, taint_type, source_or_target): 43 | self.taint_type = taint_type 44 | self.source_or_target = source_or_target 45 | 46 | self.from_object = False 47 | self.from_return = False 48 | self.from_all_parameters = False 49 | self.from_args = [] 50 | self.from_kwargs = [] 51 | 52 | self.parse_from() 53 | 54 | def parse_from(self): 55 | if not self.source_or_target: 56 | if self.taint_type == const.TAINT_SOURCE: 57 | self.from_all_parameters = True 58 | else: 59 | self.from_return = True 60 | return 61 | 62 | if self.source_or_target == 'P': 63 | self.from_all_parameters = True 64 | return 65 | 66 | splits = self.source_or_target.split('|') 67 | for sp in splits: 68 | if sp == 'O': 69 | self.from_object = True 70 | elif sp == 'R': 71 | self.from_return = True 72 | elif sp.startswith('P'): 73 | if sp == 'P': 74 | self.from_all_parameters = True 75 | if self.from_all_parameters: 76 | continue 77 | 78 | sp = sp[1:] 79 | args = sp.split(',') 80 | for arg in args: 81 | if arg.isdigit(): 82 | idx = int(arg) - 1 83 | if idx < 0: 84 | continue 85 | self.from_args.append(idx) 86 | else: 87 | self.from_kwargs.append(arg) 88 | 89 | def get_taints(self, self_obj, result, args, kwargs): 90 | taints = [] 91 | if self.from_object: 92 | taints.append(self_obj) 93 | 94 | if self.from_return: 95 | taints.append(result) 96 | 97 | if self.from_all_parameters: 98 | if args: 99 | for v in args: 100 | taints.append(v) 101 | if kwargs: 102 | for k in kwargs: 103 | taints.append(kwargs[k]) 104 | else: 105 | if args and self.from_args: 106 | for idx in self.from_args: 107 | if idx < len(args): 108 | taints.append(args[idx]) 109 | if kwargs and self.from_kwargs: 110 | for k in self.from_kwargs: 111 | if k in kwargs: 112 | taints.append(kwargs[k]) 113 | 114 | return taints 115 | -------------------------------------------------------------------------------- /dongtai_agent_python/setting/__init__.py: -------------------------------------------------------------------------------- 1 | from .setting import Setting 2 | from .config import Config 3 | -------------------------------------------------------------------------------- /dongtai_agent_python/setting/config.py: -------------------------------------------------------------------------------- 1 | import json 2 | import os 3 | 4 | 5 | class Config(object): 6 | def __init__(self): 7 | base_dir = os.path.dirname(os.path.abspath(__file__)) 8 | file_path = os.path.join(base_dir, '../config.json') 9 | with open(file_path, 'rb') as config: 10 | data = config.read() 11 | self.config = json.loads(data) 12 | 13 | def get(self, key, default=None): 14 | return self.config.get(key, default) 15 | 16 | def set(self, key, value): 17 | self.config[key] = value 18 | -------------------------------------------------------------------------------- /dongtai_agent_python/setting/const.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | CONTAINER_DJANGO = 'Django' 4 | CONTAINER_FLASK = 'Flask' 5 | 6 | NODE_TYPE_PROPAGATOR = 1 7 | NODE_TYPE_SOURCE = 2 8 | NODE_TYPE_FILTER = 3 9 | NODE_TYPE_SINK = 4 10 | 11 | NODE_TYPES = [ 12 | NODE_TYPE_PROPAGATOR, 13 | NODE_TYPE_SOURCE, 14 | NODE_TYPE_FILTER, 15 | NODE_TYPE_SINK, 16 | ] 17 | 18 | TAINT_SOURCE = 1 19 | TAINT_TARGET = 2 20 | 21 | EMPTY_PATTERN = type(re.compile('')) 22 | 23 | C_API_PATCHES = [ 24 | 'builtins.str.fstring', 25 | 'builtins.str.cformat', 26 | 'builtins.bytes.cformat', 27 | 'builtins.bytearray.cformat', 28 | 'builtins.str.__new__', 29 | 'builtins.bytes.__new__', 30 | 'builtins.bytearray.__init__', 31 | 'builtins.str.__add__', 32 | 'builtins.bytes.__add__', 33 | 'builtins.bytearray.__add__', 34 | ] 35 | 36 | CRYPTO_BAD_CIPHER_NEW = [ 37 | 'Crypto.Cipher.Blowfish.new', 38 | 'Crypto.Cipher.DES.new', 39 | 'Cryptodome.Cipher.Blowfish.new', 40 | 'Cryptodome.Cipher.DES.new', 41 | ] 42 | 43 | RESPONSE_SIGNATURES = [ 44 | 'django.http.response.HttpResponse.__init__', 45 | ] 46 | -------------------------------------------------------------------------------- /dongtai_agent_python/setting/setting.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from dongtai_agent_python import version 4 | from .config import Config 5 | from dongtai_agent_python.utils import Singleton 6 | 7 | 8 | class Setting(Singleton): 9 | loaded = False 10 | 11 | def init(self): 12 | if Setting.loaded: 13 | return 14 | 15 | self.version = version.__version__ 16 | self.paused = False 17 | self.manual_paused = False 18 | self.agent_id = 0 19 | self.request_seq = 0 20 | 21 | self.auto_create_project = 0 22 | self.use_local_policy = False 23 | self.disable_heartbeat = False 24 | self.os_env_list = [] 25 | 26 | self.policy = {} 27 | 28 | self.container = {} 29 | 30 | self.config = Config() 31 | self.debug = self.config.get("debug", False) 32 | self.project_name = self.config.get('project', {}).get('name', 'Demo Project') 33 | self.project_version = self.config.get('project', {}).get('version', '') 34 | # engine.name will auto generated when download 35 | self.engine_name = self.config.get('engine', {}).get('name', 'dongtai-agent-python') 36 | self.log_path = self.config.get("log", {}).get("log_path", "./dongtai_py_agent.log") 37 | 38 | self.init_os_environ() 39 | Setting.loaded = True 40 | 41 | def set_container(self, container): 42 | if container and isinstance(container, dict): 43 | self.container = container 44 | 45 | def init_os_environ(self): 46 | os_env = dict(os.environ) 47 | if not isinstance(os_env, dict): 48 | return 49 | 50 | if os_env.get('DEBUG', '') == '1': 51 | self.debug = True 52 | 53 | # windows always upper case env key 54 | project_name = os_env.get('PROJECT_NAME', '') or os_env.get('PROJECTNAME', '') or os_env.get('projectName', '') 55 | if project_name: 56 | self.project_name = project_name 57 | 58 | if os_env.get('PROJECT_VERSION', ''): 59 | self.project_version = os_env.get('PROJECT_VERSION', '') 60 | 61 | if os_env.get('ENGINE_NAME', ''): 62 | self.engine_name = os_env.get('ENGINE_NAME', '') 63 | 64 | if os_env.get('AUTO_CREATE_PROJECT', '') == '1': 65 | self.auto_create_project = 1 66 | 67 | if os_env.get('USE_LOCAL_POLICY', '') == '1': 68 | self.use_local_policy = True 69 | 70 | if os_env.get('DISABLE_HEARTBEAT', '') == '1': 71 | self.disable_heartbeat = True 72 | 73 | if os_env.get('LOG_PATH', ''): 74 | self.log_path = os_env.get('LOG_PATH', '') 75 | 76 | for key in os_env.keys(): 77 | self.os_env_list.append(key + '=' + str(os_env[key])) 78 | 79 | def is_agent_paused(self): 80 | return self.paused and self.manual_paused 81 | 82 | def incr_request_seq(self): 83 | self.request_seq = self.request_seq + 1 84 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/tests/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/tests/policy/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/tests/policy/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/tests/policy/test_policy.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dongtai_agent_python.policy import policy 4 | from dongtai_agent_python.setting import const 5 | 6 | 7 | class TestPolicy(unittest.TestCase): 8 | def test_policy_rule(self): 9 | detail = { 10 | "track": "true", 11 | "value": "os.system", 12 | "inherit": "false" 13 | } 14 | # invalid rule type 15 | p = policy.new_policy_rule(-1, detail) 16 | self.assertIsNone(p) 17 | 18 | detail = { 19 | "track": "true", 20 | "value": "os.system", 21 | "inherit": "false" 22 | } 23 | p = policy.new_policy_rule(const.NODE_TYPE_PROPAGATOR, detail) 24 | self.assertTrue(p.source_from.from_all_parameters) 25 | self.assertTrue(p.target_from.from_return) 26 | 27 | detail = { 28 | "source": "P1,4,k5,3,k2", 29 | "track": "true", 30 | "target": "R", 31 | "value": "os.system", 32 | "inherit": "false" 33 | } 34 | p = policy.new_policy_rule(const.NODE_TYPE_PROPAGATOR, detail) 35 | self.assertFalse(p.source_from.from_object) 36 | self.assertFalse(p.source_from.from_return) 37 | self.assertFalse(p.source_from.from_all_parameters) 38 | self.assertEqual(p.source_from.from_args, set([0, 3, 2])) 39 | self.assertEqual(p.source_from.from_kwargs, set(['k5', 'k2'])) 40 | self.assertTrue(p.target_from.from_return) 41 | self.assertFalse(p.target_from.from_object) 42 | self.assertFalse(p.target_from.from_all_parameters) 43 | 44 | detail = { 45 | "source": "O", 46 | "track": "true", 47 | "target": "P1", 48 | "value": "os.system", 49 | "inherit": "false" 50 | } 51 | p = policy.new_policy_rule(const.NODE_TYPE_PROPAGATOR, detail) 52 | self.assertTrue(p.source_from.from_object) 53 | self.assertFalse(p.source_from.from_return) 54 | self.assertFalse(p.source_from.from_all_parameters) 55 | self.assertEqual(p.target_from.from_args, set([0])) 56 | 57 | detail = { 58 | "source": "O|P", 59 | "track": "true", 60 | "target": "O|R", 61 | "value": "os.system", 62 | "inherit": "false" 63 | } 64 | p = policy.new_policy_rule(const.NODE_TYPE_PROPAGATOR, detail) 65 | self.assertTrue(p.source_from.from_object) 66 | self.assertFalse(p.source_from.from_return) 67 | self.assertTrue(p.source_from.from_all_parameters) 68 | self.assertTrue(p.target_from.from_object) 69 | self.assertTrue(p.target_from.from_return) 70 | self.assertFalse(p.target_from.from_all_parameters) 71 | 72 | 73 | if __name__ == '__main__': 74 | unittest.main() 75 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/policy/test_tracking.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dongtai_agent_python.policy import tracking 4 | 5 | 6 | class TestTracking(unittest.TestCase): 7 | def test_yaml_load_is_safe(self): 8 | try: 9 | import yaml 10 | self.assertFalse(tracking.yaml_load_is_safe(('test', yaml.UnsafeLoader), None)) 11 | self.assertFalse(tracking.yaml_load_is_safe(('test',), {'Loader': yaml.UnsafeLoader})) 12 | self.assertTrue(tracking.yaml_load_is_safe(('test',), None)) 13 | 14 | yaml.__version__ = '5.0' 15 | self.assertFalse(tracking.yaml_load_is_safe(('test',), None)) 16 | except ImportError: 17 | pass 18 | 19 | 20 | if __name__ == '__main__': 21 | unittest.main() 22 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/setting/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/tests/setting/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/tests/setting/test_setting.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import unittest 3 | 4 | from dongtai_agent_python.setting.setting import Setting 5 | 6 | 7 | class TestSetting(unittest.TestCase): 8 | def test_multithreading(self): 9 | def test(name): 10 | st1 = Setting() 11 | st1.set_container({'name': name, 'version': '0.1'}) 12 | st1.incr_request_seq() 13 | 14 | thread_num = 5 15 | for i in range(thread_num): 16 | t = threading.Thread(target=test, args=['test' + str(i)]) 17 | t.start() 18 | 19 | st = Setting() 20 | self.assertEqual(thread_num, st.request_seq) 21 | 22 | 23 | if __name__ == '__main__': 24 | unittest.main() 25 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-python/93c56d48d69b0e93892a6cb68e70de05596cb902/dongtai_agent_python/tests/utils/__init__.py -------------------------------------------------------------------------------- /dongtai_agent_python/tests/utils/test_scope.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import unittest 3 | 4 | from dongtai_agent_python.utils import scope 5 | 6 | 7 | class TestScope(unittest.TestCase): 8 | def test_scope(self): 9 | self.assertEqual('', scope.current_scope()) 10 | self.assertFalse(scope.in_scope('test1')) 11 | 12 | with scope.scope('test1'): 13 | self.assertEqual('test1', scope.current_scope()) 14 | self.assertTrue(scope.in_scope('test1')) 15 | self.assertFalse(scope.in_scope('test2')) 16 | 17 | with scope.scope('test2'): 18 | self.assertEqual('test2', scope.current_scope()) 19 | self.assertTrue(scope.in_scope('test1')) 20 | self.assertTrue(scope.in_scope('test2')) 21 | self.assertEqual('test2', scope.current_scope()) 22 | 23 | self.assertFalse(scope.in_scope('test2')) 24 | self.assertTrue(scope.in_scope('test1')) 25 | self.assertFalse(scope.in_scope('test1')) 26 | 27 | def test_multithreading(self): 28 | thread_num = 5 29 | for i in range(thread_num): 30 | t = threading.Thread(target=self.test_scope) 31 | t.start() 32 | 33 | def test_decorator(self): 34 | @scope.with_scope('test1') 35 | def test1(): 36 | self.assertTrue(scope.in_scope('test1')) 37 | return 1 38 | 39 | @scope.with_scope('test2') 40 | def test2(): 41 | self.assertTrue(scope.in_scope('test2')) 42 | test1() 43 | self.assertFalse(scope.in_scope('test1')) 44 | return 2 45 | 46 | t1 = test1() 47 | t2 = test2() 48 | self.assertFalse(scope.in_scope('test1')) 49 | self.assertFalse(scope.in_scope('test2')) 50 | self.assertEqual(1, t1) 51 | self.assertEqual(2, t2) 52 | 53 | 54 | if __name__ == '__main__': 55 | unittest.main() 56 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/utils/test_singleton.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import unittest 3 | 4 | from dongtai_agent_python.utils.singleton import Singleton 5 | 6 | 7 | class TestSingleton(unittest.TestCase): 8 | def test_singleton(self): 9 | class Test(Singleton): 10 | def init(self, seq=0): 11 | self.seq = seq 12 | 13 | def incr(self): 14 | self.seq = self.seq + 1 15 | 16 | s1 = Test(1) 17 | s2 = Test(2) 18 | self.assertEqual(s1, s2) 19 | self.assertEqual(1, s1.seq) 20 | 21 | s1.incr() 22 | s2.incr() 23 | self.assertEqual(3, s1.seq) 24 | 25 | def test_multithreading(self): 26 | class Test(Singleton): 27 | def init(self, seq=0): 28 | self.seq = seq 29 | 30 | def incr(self): 31 | self.seq = self.seq + 1 32 | 33 | def test_incr(): 34 | s1 = Test() 35 | s1.incr() 36 | 37 | thread_num = 5 38 | for i in range(thread_num): 39 | t = threading.Thread(target=test_incr) 40 | t.start() 41 | 42 | s = Test() 43 | self.assertEqual(thread_num, s.seq) 44 | 45 | 46 | if __name__ == '__main__': 47 | unittest.main() 48 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/utils/test_utils.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from dongtai_agent_python.utils import utils 4 | 5 | 6 | class TestUtils(unittest.TestCase): 7 | def test_get_packages(self): 8 | packages = utils.get_packages() 9 | for package in packages: 10 | print(package) 11 | 12 | 13 | if __name__ == '__main__': 14 | unittest.main() 15 | -------------------------------------------------------------------------------- /dongtai_agent_python/tests/vul-test.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | FRAMEWORK=$1 4 | API_URL=$2 5 | RUN_ID=$3 6 | if [ -z "${API_URL}" ]; then 7 | echo -e "api url required!" 8 | echo -e "Usage: $( basename "$0" ) " 9 | exit 1 10 | fi 11 | 12 | headline() { 13 | local TITLE=$1 14 | echo 15 | echo "########################## ${TITLE} ##########################" 16 | echo 17 | } 18 | 19 | failed() { 20 | local MSG=$1 21 | echo -e "\e[0;31m${MSG}\e[0m" 22 | } 23 | 24 | curl_with_code() { 25 | code=0 26 | # Run curl in a separate command, capturing output of -w "%{http_code}" into statuscode 27 | # and sending the content to a file with -o >(cat >/tmp/curl_body) 28 | status_code=$(curl --no-progress-meter -w "%{http_code}" \ 29 | -o >(cat >/tmp/curl_body) \ 30 | "$@" 31 | ) || code="$?" 32 | body="$(cat /tmp/curl_body)" 33 | 34 | if [[ $code -ne 0 ]]; then 35 | failed "request failed" 36 | fi 37 | if [[ $status_code -ne "200" ]]; then 38 | failed "response error: $status_code" 39 | fi 40 | echo $body 41 | echo 42 | } 43 | 44 | api_get() { 45 | local API_PATH=$1 46 | local QUERY=$2 47 | 48 | echo "=========================== ${FRAMEWORK} GET /${API_PATH}" 49 | echo 50 | curl_with_code "${API_URL}/${API_PATH}?_r=${RUN_ID}&${QUERY}" 51 | echo 52 | } 53 | 54 | api_post() { 55 | local API_PATH=$1 56 | local DATA=$2 57 | 58 | echo "=========================== ${FRAMEWORK} POST /${API_PATH}" 59 | echo 60 | curl_with_code "${API_URL}/${API_PATH}?_r=${RUN_ID}" -X POST --data-raw ${DATA} 61 | echo 62 | } 63 | 64 | headline "exec-command" 65 | api_post "demo/exec_post_popen" "code=ls" 66 | api_post "demo/exec_post_subprocess" "cmd=cat&name=%2Fetc%2Fpasswd" 67 | api_post "demo/cmd_exec" "cmd=whoami" 68 | api_post "demo/exec_post_e" "code=whoami" 69 | 70 | headline "exec-code" 71 | api_post "demo/eval_post_e" "code=__import__%28%27os%27%29.system%28%27whoami%27%29" 72 | 73 | headline "path-traversal" 74 | api_get "demo/get_open" "name=Data**" 75 | api_post "demo/post_open" "name=.%2Ffile%2Fdata.json" 76 | 77 | headline "sql-injection" 78 | if [[ "x${FRAMEWORK}" == "xdjango" ]]; then 79 | api_post "demo/postgresql_post_many" "id=100000&name=song&phone1=13300000000" 80 | fi 81 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 82 | api_post "demo/postgresql_post_many" "id=200000&name=song&phone1=13300000000" 83 | fi 84 | api_post "demo/postgresql_post_excute" "name=song" 85 | api_post "demo/mysql_post_many" "name=song&phone1=13300000000" 86 | api_post "demo/mysql_post_exec" "name=song" 87 | api_post "demo/sqlite3_post_executemany_sql" "phone1=13300000000" 88 | api_post "demo/sqlite3_post_executescript" "name=song&phone1=13300000000" 89 | api_post "demo/sqlite3_post" "name=song" 90 | 91 | headline "xss" 92 | api_get "demo/xss_return" "content=alert" 93 | api_get "demo/xss_template" "content=alert" 94 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 95 | api_get "demo/xss_template_string" "content=alert" 96 | fi 97 | 98 | headline "xxe" 99 | curl_with_code -H "Content-Type: text/plain" "${API_URL}/demo/xxe_login?_r=${RUN_ID}" -X POST --data-raw ']>&xxe;yzx' 100 | 101 | headline "ssrf" 102 | api_get "demo/urllib_ssrf" "url=https://www.huoxian.cn/" 103 | api_get "demo/request_ssrf" "url=https://www.huoxian.cn/" 104 | 105 | headline "unsafe-deserialization" 106 | api_post "demo/yaml_post_e" "code=whoami" 107 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 108 | api_post "demo/get_pickle_data" "code=gASVIQAAAAAAAACMBXBvc2l4lIwGc3lzdGVtlJOUjAZ3aG9hbWmUhZRSlC4=" 109 | fi 110 | 111 | headline "nosql-injection" 112 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 113 | api_get "demo/mongo_find" "name=%27%20||%20%27%27%20==%20%27" 114 | fi 115 | 116 | headline "ldap-injection" 117 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 118 | api_get "demo/ldap_search" "username=*&password=*" 119 | api_get "demo/ldap_safe_search" "username=*&password=*" 120 | api_get "demo/ldap3_search" "username=*&password=*" 121 | api_get "demo/ldap3_safe_search" "username=*&password=*" 122 | fi 123 | 124 | headline "crypto-bad-cipher" 125 | if [[ "x${FRAMEWORK}" == "xflask" ]]; then 126 | api_get "demo/crypto/aes" "text=content" 127 | api_get "demo/crypto/blowfish" "text=content" 128 | api_get "demo/crypto/des" "text=content" 129 | api_get "demo/cryptox/blowfish" "text=content" 130 | api_get "demo/cryptox/des" "text=content" 131 | fi 132 | -------------------------------------------------------------------------------- /dongtai_agent_python/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .singleton import Singleton 2 | from .system_info import SystemInfo 3 | -------------------------------------------------------------------------------- /dongtai_agent_python/utils/scope.py: -------------------------------------------------------------------------------- 1 | import threading 2 | from contextlib import contextmanager 3 | 4 | SCOPE_AGENT = 'agent' 5 | 6 | 7 | class ScopeContext(threading.local): 8 | def __init__(self): 9 | self._active_scopes = [] 10 | 11 | @property 12 | def active_scopes(self): 13 | return self._active_scopes[:] 14 | 15 | @property 16 | def current_scope(self): 17 | if len(self._active_scopes) == 0: 18 | return '' 19 | return self._active_scopes[-1][:] # Slice to get copy. 20 | 21 | def enter_scope(self, name): 22 | """Enters the given scope, updating the list of active scopes. 23 | Args: 24 | name: scope name 25 | """ 26 | self._active_scopes = self._active_scopes + [name] 27 | 28 | def exit_scope(self): 29 | """Exits the most recently entered scope.""" 30 | self._active_scopes = self._active_scopes[:-1] 31 | 32 | def in_scope(self, name): 33 | return name in self._active_scopes 34 | 35 | 36 | SCOPE_CONTEXT = ScopeContext() 37 | 38 | 39 | @contextmanager 40 | def scope(name): 41 | SCOPE_CONTEXT.enter_scope(name) 42 | try: 43 | yield 44 | finally: 45 | SCOPE_CONTEXT.exit_scope() 46 | 47 | 48 | def with_scope(name): 49 | def wrapper(original_func): 50 | def _wrapper(*args, **kwargs): 51 | with scope(name): 52 | return_value = original_func(*args, **kwargs) 53 | return return_value 54 | return _wrapper 55 | return wrapper 56 | 57 | 58 | def current_scope(): 59 | return SCOPE_CONTEXT.current_scope 60 | 61 | 62 | def enter_scope(name): 63 | return SCOPE_CONTEXT.enter_scope(name) 64 | 65 | 66 | def exit_scope(): 67 | return SCOPE_CONTEXT.exit_scope() 68 | 69 | 70 | def in_scope(name): 71 | return SCOPE_CONTEXT.in_scope(name) 72 | -------------------------------------------------------------------------------- /dongtai_agent_python/utils/singleton.py: -------------------------------------------------------------------------------- 1 | # @see: https://www.python.org/download/releases/2.2/descrintro/#__new__ 2 | 3 | 4 | class Singleton(object): 5 | def __new__(cls, *args, **kwargs): 6 | it = cls.__dict__.get("__it__") 7 | if it is not None: 8 | return it 9 | cls.__it__ = it = object.__new__(cls) 10 | it.init(*args, **kwargs) 11 | return it 12 | 13 | def init(self, *args, **kwargs): 14 | pass 15 | -------------------------------------------------------------------------------- /dongtai_agent_python/utils/system_info.py: -------------------------------------------------------------------------------- 1 | from dongtai_agent_python.common.logger import logger_config 2 | from dongtai_agent_python.utils import scope 3 | 4 | logger = logger_config('system_info') 5 | 6 | 7 | class SystemInfo(object): 8 | def __init__(self): 9 | self.unit = 1024 * 1024 * 1024 10 | try: 11 | import psutil 12 | self.psutil = psutil 13 | logger.info("psutil import success") 14 | except Exception: 15 | self.psutil = None 16 | logger.error("psutil import error, please install psutil") 17 | 18 | # 获取网络信息 19 | @scope.with_scope(scope.SCOPE_AGENT) 20 | def print_net_if_addr(self): 21 | if self.psutil is not None: 22 | try: 23 | dic = self.psutil.net_if_addrs() 24 | network_arr = [] 25 | for adapter in dic: 26 | snic_list = dic[adapter] 27 | mac = '无 mac 地址' 28 | ipv4 = '无 ipv4 地址' 29 | ipv6 = '无 ipv6 地址' 30 | for snic in snic_list: 31 | if snic.family.name in {'AF_LINK', 'AF_PACKET'}: 32 | mac = snic.address 33 | elif snic.family.name == 'AF_INET': 34 | ipv4 = snic.address 35 | elif snic.family.name == 'AF_INET6': 36 | ipv6 = snic.address 37 | network_arr.append('%s, %s, %s, %s' % (adapter, mac, ipv4, ipv6)) 38 | logger.info("get network success") 39 | return ';'.join(network_arr) 40 | except Exception as e: 41 | logger.error("get network" + str(e)) 42 | return '' 43 | else: 44 | return '' 45 | 46 | # 获取cpu信息 47 | @scope.with_scope(scope.SCOPE_AGENT) 48 | def get_cpu_rate(self): 49 | if self.psutil is not None: 50 | # print(self.psutil.cpu_percent()) 51 | percent = self.psutil.cpu_percent() 52 | return percent 53 | else: 54 | return 0 55 | 56 | # 获取系统内存使用情况 57 | @scope.with_scope(scope.SCOPE_AGENT) 58 | def get_memory_info(self): 59 | if self.psutil is not None: 60 | memory_info = self.psutil.virtual_memory() 61 | return { 62 | 'total': round(memory_info.total / self.unit, 2), 63 | 'used': round(memory_info.used / self.unit, 2), 64 | 'rate': memory_info.percent 65 | } 66 | else: 67 | return { 68 | 'total': 0, 69 | 'use': 0, 70 | 'rate': 0 71 | } 72 | 73 | # 获取磁盘信息 74 | @scope.with_scope(scope.SCOPE_AGENT) 75 | def get_disk(self): 76 | disk = {'info': []} 77 | if self.psutil is not None: 78 | devs = self.psutil.disk_partitions() 79 | if devs: 80 | for dev in devs: 81 | disk_info = self.psutil.disk_usage(dev.mountpoint) 82 | # 将字节转换成G 83 | disk['info'].append({ 84 | 'name': dev.device, 85 | 'total': str(round(disk_info.total / self.unit, 2)) + 'G', 86 | 'used': str(round(disk_info.used / self.unit, 2)) + 'G', 87 | 'free': str(round(disk_info.free / self.unit, 2)) + 'G', 88 | 'rate': str(disk_info.percent) + '%', 89 | 'fstype': dev.fstype 90 | }) 91 | return disk 92 | -------------------------------------------------------------------------------- /dongtai_agent_python/utils/utils.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import hashlib 3 | import os 4 | 5 | import pkg_resources 6 | 7 | from dongtai_agent_python.assess_ext import c_api 8 | from dongtai_agent_python.setting import const 9 | from dongtai_agent_python.utils import scope 10 | 11 | 12 | @scope.with_scope(scope.SCOPE_AGENT) 13 | def normalize_response_header(status_line, headers): 14 | header_str = status_line + "\r\n" + json_to_str(headers) 15 | header_str = base64.b64encode(header_str.encode('utf-8')) 16 | header_str = bytes.decode(header_str, 'utf-8') 17 | return header_str 18 | 19 | 20 | @scope.with_scope(scope.SCOPE_AGENT) 21 | def json_to_base64(json_data): 22 | if json_data: 23 | json_data = json_to_str(json_data) 24 | json_data = base64.b64encode(json_data.encode('utf-8')) 25 | json_data = bytes.decode(json_data, 'utf-8') 26 | return json_data 27 | 28 | 29 | @scope.with_scope(scope.SCOPE_AGENT) 30 | def bytes_to_base64(data): 31 | b64_data = base64.b64encode(data) 32 | return bytes.decode(b64_data, 'utf-8') 33 | 34 | 35 | def json_to_str(json_data): 36 | if json_data: 37 | new_list = [] 38 | for item in json_data.keys(): 39 | new_list.append(str(item) + ": " + str(json_data[item])) 40 | json_data = "\r\n".join(new_list) 41 | return json_data 42 | 43 | 44 | def is_empty(value): 45 | if value is None: 46 | return True 47 | if isinstance(value, (tuple, list, dict, str, bytes, bytearray)): 48 | return not value 49 | return False 50 | 51 | 52 | def is_not_allowed_type(value): 53 | return type(value) == int or type(value) == bool 54 | 55 | 56 | def needs_propagation(context, node_type): 57 | if context is None or (node_type != const.NODE_TYPE_SOURCE and not context.has_source): 58 | return False 59 | 60 | return True 61 | 62 | 63 | # @TODO: improve performance 64 | def get_hash(item): 65 | try: 66 | h = hashlib.md5((c_api.str_origin(id(item)) + ":" + c_api.str_origin(item)).encode('utf-8')).hexdigest() 67 | except Exception: 68 | h = id(item) 69 | return h 70 | 71 | 72 | def get_packages(): 73 | packages = pkg_resources.working_set 74 | sca_packages = [] 75 | for package in packages: 76 | module_path = package.location + os.sep + package.project_name.lower() 77 | found = False 78 | if os.path.exists(module_path): 79 | found = True 80 | 81 | if not found: 82 | module_path = package.location + os.sep + package.project_name.replace('-', '_') 83 | if os.path.exists(module_path): 84 | found = True 85 | 86 | if not found: 87 | module_path = package.location + os.sep + package.project_name 88 | if os.path.exists(module_path): 89 | found = True 90 | 91 | if not found and package.has_metadata('top_level.txt'): 92 | top_level = package.get_metadata('top_level.txt').splitlines() 93 | if top_level: 94 | for lvl in top_level: 95 | if os.path.exists(package.location + os.sep + lvl): 96 | module_path = package.location + os.sep + lvl 97 | 98 | package_name = 'pypi:' + package.project_name.lower() + ':' + package.version + ':' 99 | sha_1 = hashlib.sha1() 100 | sha_1.update(bytes(package_name, encoding='utf-8')) 101 | digest = sha_1.hexdigest() 102 | 103 | sca_packages.append({ 104 | 'packageName': package_name, 105 | 'packageVersion': package.version, 106 | 'packagePath': module_path, 107 | 'packageAlgorithm': 'SHA-1', 108 | 'packageSignature': digest, 109 | }) 110 | return sca_packages 111 | -------------------------------------------------------------------------------- /dongtai_agent_python/version.py: -------------------------------------------------------------------------------- 1 | __version__ = '1.4.0' 2 | -------------------------------------------------------------------------------- /scripts/dongtai-cli: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from dongtai_agent_python import cli 4 | 5 | cli.main() 6 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | name = dongtai_agent_python 3 | version = attr: dongtai_agent_python.version.__version__ 4 | description = DongTai IAST Agent for Python 5 | long_description = file: README.md 6 | url = https://dongtai.io 7 | author = songjinghao 8 | author_email = jinghaosong@huoxian.cn 9 | license = Apache License 2.0 10 | license_file = LICENSE 11 | classifiers = 12 | Environment :: Web Environment 13 | Framework :: Django 14 | Framework :: Flask 15 | Intended Audience :: Developers 16 | License :: OSI Approved :: Apache Software License 17 | Operating System :: OS Independent 18 | Programming Language :: Python 19 | Programming Language :: Python :: 3 20 | Programming Language :: Python :: 3 :: Only 21 | Topic :: Internet :: WWW/HTTP 22 | Topic :: Internet :: WWW/HTTP :: Dynamic Content 23 | 24 | [options] 25 | include_package_data = true 26 | packages = find: 27 | python_requires = >=3.6 28 | install_requires = 29 | psutil >= 5.8.0 30 | requests >= 2.25.1 31 | pip >= 19.2.3 32 | ; regexploit >= 1.0.0 33 | --------------------------------------------------------------------------------