├── .github └── workflows │ ├── run-unittest.yml │ └── scripts │ └── run-govwa.sh ├── .gitignore ├── LICENSE ├── README.md ├── README_zh.md ├── api ├── base_config.go ├── engine.go └── webapi.go ├── core ├── base │ ├── bufferWriteString │ │ ├── install.go │ │ └── replacement.go │ ├── bufioWriterWrite │ │ ├── instrall.go │ │ └── replacement.go │ ├── bufioWriterWriteString │ │ ├── instrall.go │ │ └── replacement.go │ ├── builderWriteString │ │ ├── install.go │ │ └── replacement.go │ ├── execCmdStart │ │ ├── install.go │ │ └── replacement.go │ ├── execCommand │ │ ├── install.go │ │ └── replacement.go │ ├── fmtSprintf │ │ ├── install.go │ │ └── replacement.go │ ├── htmlTemplateExecuteTemplate │ │ ├── install.go │ │ └── replacement.go │ ├── httpClientDo │ │ ├── install.go │ │ └── replacement.go │ ├── httpNewRequest │ │ ├── install.go │ │ └── replacement.go │ ├── ioReadAll │ │ ├── install.go │ │ └── replacement.go │ ├── jsonDecoderDecode │ │ ├── install.go │ │ └── replacement.go │ ├── jsonNewDecoder │ │ ├── install.go │ │ └── replacement.go │ ├── jsonUnmarshal │ │ ├── install.go │ │ └── replacement.go │ ├── osOpenFile │ │ ├── install.go │ │ └── replacement.go │ ├── regexpRegexpReplaceAllString │ │ ├── install.go │ │ └── replacement.go │ ├── runtimeConcatstrings │ │ ├── empty.s │ │ ├── install.go │ │ └── replacement.go │ ├── runtimeMapassign_faststr │ │ ├── empty.s │ │ ├── install.go │ │ └── replacement.go │ ├── runtimeSlicebytetostring │ │ ├── empty.s │ │ ├── install.go │ │ └── replacement.go │ ├── runtimesSringtoslicebyte │ │ ├── empty.s │ │ ├── install.go │ │ └── replacement.go │ ├── sqlDBQuery │ │ ├── install.go │ │ └── replacement.go │ ├── stringsBuilderWriteString │ │ ├── install.go │ │ └── replacement.go │ ├── stringsJoin │ │ ├── install.go │ │ └── replacement.go │ ├── stringsRepeat │ │ ├── install.go │ │ └── replacement.go │ ├── stringsReplace │ │ ├── install.go │ │ └── replacement.go │ └── urlUrlString │ │ ├── install.go │ │ └── replacement.go ├── gin │ ├── ginContextGetPostFormArray │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextGetPostFormMap │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextGetQueryArray │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextGetQueryMap │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextParam │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextShouldBindBodyWith │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextShouldBindUri │ │ ├── install.go │ │ └── replacement.go │ ├── ginContextShouldBindWith │ │ ├── install.go │ │ └── replacement.go │ └── ginEngineServerHTTP │ │ ├── install.go │ │ └── replacement.go ├── goChi │ └── httpRouter │ │ ├── install.go │ │ └── replacement.go ├── gorilla │ └── gorillaRpcServerHTTP │ │ ├── install.go │ │ └── replacement.go ├── gorm │ ├── gormDBExec │ │ ├── install.go │ │ └── replacement.go │ ├── gormDBGroup │ │ ├── install.go │ │ └── replacement.go │ ├── gormDBHaving │ │ ├── install.go │ │ └── replacement.go │ ├── gormDBOrder │ │ ├── install.go │ │ └── replacement.go │ ├── gormDBPluck │ │ ├── install.go │ │ └── replacement.go │ ├── gormDBRaw │ │ ├── install.go │ │ └── replacement.go │ └── gormDBSelect │ │ ├── install.go │ │ └── replacement.go ├── grpc │ ├── clientConn │ │ ├── install.go │ │ └── replacement.go │ └── newServer │ │ ├── install.go │ │ └── replacement.go ├── http │ ├── httpHeaderGet │ │ ├── install.go │ │ └── replacement.go │ ├── httpRequestCookie │ │ ├── install.go │ │ └── replacement.go │ ├── httpRequestFormValue │ │ ├── install.go │ │ └── replacement.go │ ├── httpServeHTTP │ │ ├── install.go │ │ └── replacement.go │ └── urlURLQuery │ │ ├── install.go │ │ └── replacement.go ├── httpRouter │ └── httpRouter │ │ ├── install.go │ │ └── replacement.go ├── kafkaGo │ └── kafkaWriter │ │ ├── install.go │ │ └── replacement.go └── mux │ └── muxServerHTTP │ ├── install.go │ └── replacement.go ├── global ├── config.go └── status.go ├── go.mod ├── go.sum ├── hook ├── base.go ├── gin.go ├── goChi.go ├── gorilla.go ├── gorm.go ├── grpc.go ├── hook.go ├── http.go ├── httpRouter.go ├── kafkaGo.go └── mux.go ├── model ├── config.go ├── hook_base.go ├── request │ └── engine.go └── response │ └── engine.go ├── run ├── base │ └── base.go ├── chiRouter │ └── hookChiRouter.go ├── gin │ └── hookGin.go ├── gorilla │ └── hookGorilla.go ├── gorm │ └── hookGorm.go ├── grpc │ └── grpc.go ├── http │ └── hookHttp.go ├── httpRouter │ └── hookHttpRouter.go ├── kafkaGo │ └── kafkaGo.go └── mux │ └── hookMux.go ├── service ├── auxiliarygt18.go ├── auxiliarylt18.go ├── engine.go ├── version │ └── exe.go └── xcoff │ ├── ar.go │ ├── file.go │ └── xcoff.go └── utils ├── cat_goroutine.go ├── fmt_stack.go ├── getIp.go ├── get_string_source.go ├── gzip.go ├── is_hook.go ├── range_struct_filed.go ├── server.go ├── sha1.go ├── snowFlake.go └── string_add.go /.github/workflows/run-unittest.yml: -------------------------------------------------------------------------------- 1 | name: Run UnitTest 2 | 3 | on: 4 | pull_request: 5 | paths-ignore: 6 | - '.github/**' 7 | - 'changes/**' 8 | - 'deploy/**' 9 | - '**.md' 10 | - '**.yml' 11 | - '**.xml' 12 | - 'LICENSE' 13 | - '.gitignore' 14 | 15 | jobs: 16 | Run-Go-CI: 17 | name: Run Go Agent CI 18 | runs-on: ubuntu-latest 19 | if: github.event_name == 'push' 20 | steps: 21 | - uses: joelwmale/webhook-action@master 22 | with: 23 | url: ${{ secrets.DONGTAI_WEBHOOK_URL }} 24 | body: '{"msg_type": "interactive","card": {"config": {"wide_screen_mode": true,"enable_forward": true},"elements": [{"tag": "div","text": {"content": "状态:项目${{github.repository}}构建开始\n分支:${{github.ref}}\n流程:${{github.workflow}}\n构建编号:${{github.run_number}}\n触发事件:${{github.event_name}}\n提交人:${{github.actor}}\nSHA-1:${{github.sha}}\n","tag": "lark_md"}}]}}' 25 | 26 | Test-Agent: 27 | name: Update this repo's README 28 | runs-on: ubuntu-latest 29 | strategy: 30 | matrix: 31 | go: [ '1.17', '1.16' ] 32 | steps: 33 | - uses: actions/checkout@v2 34 | - uses: actions/setup-go@v2 35 | with: 36 | go-version: ${{ matrix.go }} # T 37 | 38 | - run: bash .github/workflows/scripts/run-govwa.sh 39 | 40 | Finish-Go-CI: 41 | name: Finish Go CI 42 | runs-on: ubuntu-latest 43 | if: github.event_name == 'push' 44 | needs: 45 | - Test-Agent 46 | steps: 47 | - uses: joelwmale/webhook-action@master 48 | with: 49 | url: ${{ secrets.DONGTAI_WEBHOOK_URL }} 50 | body: '{"msg_type": "interactive","card": {"config": {"wide_screen_mode": true,"enable_forward": true},"elements": [{"tag": "div","text": {"content": "状态:项目${{github.repository}}构建开始\n分支:${{github.ref}}\n流程:${{github.workflow}}\n构建编号:${{github.run_number}}\n触发事件:${{github.event_name}}\n提交人:${{github.actor}}\nSHA-1:${{github.sha}}\n","tag": "lark_md"}}]}}' 51 | 52 | -------------------------------------------------------------------------------- /.github/workflows/scripts/run-govwa.sh: -------------------------------------------------------------------------------- 1 | cd /tmp 2 | git clone https://github.com/exexute/govwa.git 3 | cd /tmp/govwa 4 | 5 | # build govwa 6 | go mod tidy 7 | 8 | # run govwa 9 | nohup go run -gcflags "all=-N -l" app.go & 10 | 11 | sleep 60 12 | 13 | ps aux 14 | curl localhost:8888 15 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## for IDEA 2 | .idea 3 | .idea/* 4 | *.iml 5 | *.DS_Store 6 | 7 | ## for maven 8 | pom.xml.versionsBackup 9 | iast-core/target/ 10 | iast-inject/target/ 11 | iast-agent/target/ 12 | UnitText/target/ 13 | target/ 14 | **/dependency-reduced-pom.xml 15 | 16 | ## for eclipse and vscode 17 | .classpath 18 | .project 19 | .settings 20 | .factorypath 21 | 22 | ## for vim 23 | *.swp 24 | *.swo 25 | *.swn 26 | 27 | # for iast 28 | release 29 | 30 | # for jenv 31 | .java-version 32 | 33 | logs -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [2021] [ HXSecurity DongTai ] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ## DongTai-agent-go 2 | --- 3 | [中文文档](README_zh.md) 4 | 5 | [![license Apache-2.0](https://img.shields.io/github/license/HXSecurity/DongTai-agent-go)](https://github.com/HXSecurity/DongTai-agent-go/blob/main/LICENSE) 6 | [![GitHub stars](https://img.shields.io/github/stars/HXSecurity/DongTai-agent-go.svg?label=Stars&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 7 | [![GitHub forks](https://img.shields.io/github/forks/HXSecurity/DongTai-Agent-Go?label=Forks&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 8 | [![GitHub Contributors](https://img.shields.io/github/contributors-anon/HXSecurity/DongTai-agent-go?label=Contributors&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 9 | 10 | [![Github Version](https://img.shields.io/github/v/release/HXSecurity/DongTai-agent-go?display_name=tag&include_prereleases&sort=semver)](https://github.com/HXSecurity/DongTai-agent-go/releases) 11 | [![Release downloads](https://shields.io/github/downloads/HXSecurity/DongTai-Agent-go/total)](https://github.com/HXSecurity/DongTai-agent-go/releases) 12 | 13 | 14 | 15 | 16 | ## Project Introduction 17 | 18 | DongTai-agent-go is the data collection terminal developed by **Dongtai IAST** for Go applications. In the Go application with the iast-agent agent, the required data is collected by rewriting the assembly address, and then the data is sent to the DongTai-openapi service, and the cloud engine processes the data to determine whether there are security vulnerabilities. 19 | 20 | DongTai-agent-go is composed of three main parts: `core`, `run`, and `service`, among which: 21 | 22 | `run` is used to run the agent of the package that needs to be instrumented on demand 23 | 24 | `core` is the core package, and its main functions are: bytecode instrumentation, data collection, data preprocessing, data reporting, third-party component management, etc. 25 | 26 | `service` is used to obtain the request sent by the application and the response received, for data display and request replay function. 27 | 28 | ## Application scenario 29 | 30 | DevOps process 31 | 32 | Safety test before going live 33 | 34 | Third-party component management 35 | 36 | Code audit 37 | 38 | 0 Day mining 39 | 40 | ## Get started quickly 41 | 42 | ### Quick use 43 | 44 | Please refer to: [Quick Start](https://doc.dongtai.io) 45 | 46 | ### Rapid development 47 | 48 | 1. Fork [DongTai-agent-go](https://github.com/HXSecurity/DongTai-agent-go) project to your github repository and clone the project: 49 | 50 | ```shell 51 | git clone https://github.com//DongTai-agent-go 52 | ``` 53 | 54 | 2. Write code according to requirements 55 | 56 | 3. Contribute code. If you want to contribute code to the Dongtai IAST team, please read the complete [Contribution Guide](https://github.com/HXSecurity/DongTai/blob/main/CONTRIBUTING.md) 57 | 58 | #### Supported Go versions and middleware 59 | 60 | Go 1.11+ 61 | 62 | Gin, Gorm and other mainstream software and middleware 63 | -------------------------------------------------------------------------------- /README_zh.md: -------------------------------------------------------------------------------- 1 | ## DongTai-agent-go 2 | --- 3 | [English version](README.md) 4 | 5 | [![license Apache-2.0](https://img.shields.io/github/license/HXSecurity/DongTai-agent-go)](https://github.com/HXSecurity/DongTai-agent-go/blob/main/LICENSE) 6 | [![GitHub stars](https://img.shields.io/github/stars/HXSecurity/DongTai-agent-go.svg?label=Stars&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 7 | [![GitHub forks](https://img.shields.io/github/forks/HXSecurity/DongTai-Agent-Go?label=Forks&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 8 | [![GitHub Contributors](https://img.shields.io/github/contributors-anon/HXSecurity/DongTai-agent-go?label=Contributors&logo=github)](https://github.com/HXSecurity/DongTai-agent-go) 9 | 10 | 11 | [![Github Version](https://img.shields.io/github/v/release/HXSecurity/DongTai-agent-go?display_name=tag&include_prereleases&sort=semver)](https://github.com/HXSecurity/DongTai-agent-go/releases) 12 | [![Release downloads](https://shields.io/github/downloads/HXSecurity/DongTai-Agent-go/total)](https://github.com/HXSecurity/DongTai-agent-go/releases) 13 | 14 | 15 | 16 | ## 项目介绍 17 | 18 | DongTai-agent-go 是**洞态IAST** 针对 Go 应用开发的数据采集端。在添加 iast-agent 代理的 Go 应用中,通过改写汇编地址的方式采集所需数据,然后将数据发送至 DongTai-openapi 服务,再由云端引擎处理数据判断是否存在安全漏洞。 19 | 20 | DongTai-agent-go 由`core`、`run`、`service`三个主要部分构成,其中: 21 | 22 | - `run`用来按需运行需要插装的包的agent 23 | - `core`是核心包,其主要功能是:字节码插桩、数据采集、数据预处理、数据上报、第三方组件管理等。 24 | - `service`用于获取应用发送的请求以及收到的响应,用于数据展示以及请求重放功能。 25 | 26 | ## 应用场景 27 | 28 | - DevOps流程 29 | - 上线前安全测试 30 | - 第三方组件管理 31 | - 代码审计 32 | - 0 Day挖掘 33 | 34 | 35 | ## 快速上手 36 | 37 | ### 快速使用 38 | 39 | 请参考:[快速开始](https://doc.dongtai.io) 40 | 41 | ### 快速开发 42 | 43 | 1. Fork [DongTai-agent-go](https://github.com/HXSecurity/DongTai-agent-go) 项目到自己的github仓库并 clone 项目: 44 | 45 | ```shell 46 | git clone https://github.com//DongTai-agent-go 47 | ``` 48 | 49 | 2. 根据需求编写代码 50 | 51 | 3. 贡献代码。如果您想要向洞态 IAST 团队贡献代码,请阅读完整的[贡献指南](https://github.com/HXSecurity/DongTai/blob/main/CONTRIBUTING.md) 52 | 53 | #### 支持的Go版本及中间件 54 | 55 | - Go 1.11+ 56 | - Gin,Gorm等主流软件和中间件 57 | -------------------------------------------------------------------------------- /api/base_config.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/utils" 7 | "github.com/parnurzeal/gorequest" 8 | "time" 9 | ) 10 | 11 | // NewRequest 12 | // 空白的请求工具 预留做后续的统一参数处理 13 | func NewRequest() *gorequest.SuperAgent { 14 | request := gorequest.New() 15 | request.Timeout(30 * time.Second) 16 | return request 17 | } 18 | 19 | // POST 20 | // 统一的POST前置处理 21 | // url 请求api 22 | // token 身份标识 23 | func POST(url string, body interface{}) *gorequest.SuperAgent { 24 | s, _ := json.Marshal(body) 25 | jsonStr := utils.GzipStr(string(s)) 26 | request := NewRequest() 27 | request.Post(global.Config.DongtaiGoOpenapi+url). 28 | Set("Content-Type", "application/json"). 29 | Set("Authorization", "Token "+global.Config.DongtaiGoToken). 30 | Send(jsonStr) 31 | return request 32 | } 33 | 34 | // GET 35 | // 统一的GET前置处理 36 | // url 请求api 37 | // token 身份标识 38 | func GET(url string, body interface{}) *gorequest.SuperAgent { 39 | request := NewRequest() 40 | request.Get(global.Config.DongtaiGoOpenapi+url).Set("Authorization", "Token "+global.Config.DongtaiGoToken).Query(body) 41 | return request 42 | } 43 | -------------------------------------------------------------------------------- /api/engine.go: -------------------------------------------------------------------------------- 1 | package api 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model/request" 7 | "github.com/HXSecurity/DongTai-agent-go/model/response" 8 | "github.com/pkg/errors" 9 | ) 10 | 11 | /* AgentRegister 12 | Agent 启动时,向 Server 端注册的接口 13 | req: api.AgentRegisterReq 14 | */ 15 | func AgentRegister(req request.AgentRegisterReq) (AgentId int, err error) { 16 | fmt.Println("探针注册开始等待返回") 17 | resp, body, errs := POST("/api/v1/agent/register", req).End() 18 | fmt.Println("探针注册返回:", string(body)) 19 | if len(errs) > 0 { 20 | for _, v := range errs { 21 | fmt.Println(v) 22 | } 23 | err = errs[0] 24 | return 0, err 25 | } 26 | if resp.StatusCode == 200 { 27 | var res response.AgentRegisterRes 28 | err := json.Unmarshal([]byte(body), &res) 29 | if err != nil { 30 | return 0, err 31 | } 32 | if res.Status == 201 { 33 | AgentId = res.Data.Id 34 | fmt.Println("注册成功,探针ID为", res.Data.Id) 35 | return AgentId, nil 36 | } 37 | return 0, errors.New("注册失败,失败原因" + res.Msg) 38 | 39 | } 40 | return 0, errors.New("状态码为" + resp.Status) 41 | } 42 | 43 | func Limit() map[string]string { 44 | var limit = make(map[string]string) 45 | resp, body, errs := GET("/api/v1/agent/limit", nil).End() 46 | if len(errs) > 0 { 47 | for _, v := range errs { 48 | fmt.Println(v) 49 | } 50 | return limit 51 | } 52 | if resp.StatusCode == 200 { 53 | var res response.LimitRes 54 | err := json.Unmarshal([]byte(body), &res) 55 | if err != nil { 56 | fmt.Println(err) 57 | } 58 | for _, item := range res.Data { 59 | limit[item.Key] = item.Value 60 | } 61 | } 62 | return limit 63 | } 64 | 65 | /* Profiles 66 | Engine 运行时,从 OpenAPI 服务获取Hook规则 67 | */ 68 | func Profiles(req request.HookRuleReq) { 69 | resp, body, errs := GET("/api/v1/profiles", req).End() 70 | if len(errs) > 0 { 71 | for _, v := range errs { 72 | fmt.Println(v) 73 | } 74 | return 75 | } 76 | if resp.StatusCode == 200 { 77 | var res response.AgentRegisterRes 78 | err := json.Unmarshal([]byte(body), &res) 79 | if err != nil { 80 | fmt.Println(err) 81 | return 82 | } 83 | } 84 | } 85 | 86 | func ReportUpload(req request.UploadReq) { 87 | resp, body, errs := POST("/api/v1/report/upload", req).End() 88 | if len(errs) > 0 { 89 | for _, v := range errs { 90 | fmt.Println(v) 91 | } 92 | return 93 | } 94 | if resp.StatusCode == 200 { 95 | var res response.ResBase 96 | err := json.Unmarshal([]byte(body), &res) 97 | if res.Status == 201 { 98 | if req.Type != 1 { 99 | fmt.Println(res.Msg) 100 | } 101 | } else { 102 | if req.Type != 1 { 103 | fmt.Println(res.Msg) 104 | } 105 | } 106 | if err != nil { 107 | fmt.Println(err) 108 | return 109 | } 110 | } 111 | } 112 | -------------------------------------------------------------------------------- /api/webapi.go: -------------------------------------------------------------------------------- 1 | package api 2 | -------------------------------------------------------------------------------- /core/base/bufferWriteString/install.go: -------------------------------------------------------------------------------- 1 | package bufferWriteString 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["bufferWriteString"] = new(BufferWriteString) 12 | } 13 | 14 | type BufferWriteString struct { 15 | } 16 | 17 | func (h *BufferWriteString) Hook() { 18 | var bt bytes.Buffer 19 | err := gohook.HookMethod(bt, "WriteString", WriteString, WriteStringT) 20 | if err != nil { 21 | fmt.Println(err, "BufferWriteString") 22 | } else { 23 | fmt.Println("BufferWriteString") 24 | } 25 | } 26 | 27 | func (h *BufferWriteString) UnHook() { 28 | var bt bytes.Buffer 29 | gohook.UnHookMethod(bt, "WriteString") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/bufferWriteString/replacement.go: -------------------------------------------------------------------------------- 1 | package bufferWriteString 2 | 3 | import ( 4 | "bytes" 5 | "github.com/HXSecurity/DongTai-agent-go/model/request" 6 | ) 7 | 8 | func WriteString(b *bytes.Buffer, s string) (n int, err error) { 9 | argStr := b.String() 10 | n, err = WriteStringT(b, s) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(argStr, s), 13 | Reqs: request.Collect(b.String()), 14 | NeedHook: request.Collect(argStr, s), 15 | NeedCatch: request.Collect(b.String()), 16 | Source: false, 17 | OriginClassName: "bytes.(*Buffer)", 18 | MethodName: "WriteString", 19 | ClassName: "bytes.(*Buffer)", 20 | }) 21 | return n, err 22 | } 23 | 24 | func WriteStringT(b *bytes.Buffer, s string) (n int, err error) { 25 | return n, err 26 | } 27 | -------------------------------------------------------------------------------- /core/base/bufioWriterWrite/instrall.go: -------------------------------------------------------------------------------- 1 | package bufioWriterWrite 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "github.com/HXSecurity/DongTai-agent-go/model" 8 | "github.com/brahma-adshonor/gohook" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["bufioWriterWrite"] = new(BufioWriterWrite) 13 | } 14 | 15 | type BufioWriterWrite struct { 16 | } 17 | 18 | func (h *BufioWriterWrite) Hook() { 19 | var w *bufio.Writer 20 | err := gohook.HookMethod(w, "Write", Write, WriteT) 21 | if err != nil { 22 | fmt.Println(err, "BufioWriterWrite") 23 | } else { 24 | fmt.Println("BufioWriterWrite") 25 | } 26 | } 27 | 28 | func (h *BufioWriterWrite) UnHook() { 29 | var bt bytes.Buffer 30 | gohook.UnHookMethod(bt, "BufioWriterWrite") 31 | } 32 | -------------------------------------------------------------------------------- /core/base/bufioWriterWrite/replacement.go: -------------------------------------------------------------------------------- 1 | package bufioWriterWrite 2 | 3 | import ( 4 | "bufio" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/model/request" 7 | "github.com/HXSecurity/DongTai-agent-go/utils" 8 | "reflect" 9 | ) 10 | 11 | func Write(b *bufio.Writer, v []byte) (n int, err error) { 12 | 13 | if utils.IsHook("net/http.(*response).write", 6) { 14 | value, ok := global.ResponseMap.Load(utils.CatGoroutineID()) 15 | if ok { 16 | str := utils.StringAdd(value.(string), string(v)) 17 | global.ResponseMap.Store(utils.CatGoroutineID(), str) 18 | } else { 19 | global.ResponseMap.Store(utils.CatGoroutineID(), string(v)) 20 | } 21 | 22 | var u uintptr 23 | va := reflect.ValueOf(v) 24 | u = va.Pointer() 25 | request.FmtHookPool(request.PoolReq{ 26 | Args: request.Collect(b, v), 27 | Reqs: request.Collect(n, err), 28 | NeedHook: request.Collect(u), 29 | Source: false, 30 | OriginClassName: "bufio.(*Buffer)", 31 | MethodName: "Write", 32 | ClassName: "bufio.(*Buffer)", 33 | }) 34 | if utils.IsHook("net/http.extraHeader.Write", 6) { 35 | value, ok := global.ResponseHeaderMap.Load(utils.CatGoroutineID()) 36 | if ok { 37 | str := utils.StringAdd(value.(string), string(v)) 38 | global.ResponseHeaderMap.Store(utils.CatGoroutineID(), str) 39 | } else { 40 | global.ResponseHeaderMap.Store(utils.CatGoroutineID(), string(v)) 41 | } 42 | } 43 | } 44 | 45 | return WriteT(b, v) 46 | } 47 | 48 | func WriteT(b *bufio.Writer, v []byte) (n int, err error) { 49 | return n, err 50 | } 51 | -------------------------------------------------------------------------------- /core/base/bufioWriterWriteString/instrall.go: -------------------------------------------------------------------------------- 1 | package bufioWriterWriteString 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "fmt" 7 | "github.com/HXSecurity/DongTai-agent-go/model" 8 | "github.com/brahma-adshonor/gohook" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["bufioWriterWriteString"] = new(BufioWriterWriteString) 13 | } 14 | 15 | type BufioWriterWriteString struct { 16 | } 17 | 18 | func (h *BufioWriterWriteString) Hook() { 19 | var w *bufio.Writer 20 | err := gohook.HookMethod(w, "WriteString", WriteString, WriteStringT) 21 | if err != nil { 22 | fmt.Println(err, "BufioWriterWriteString") 23 | } else { 24 | fmt.Println("BufioWriterWriteString") 25 | } 26 | } 27 | 28 | func (h *BufioWriterWriteString) UnHook() { 29 | var bt bytes.Buffer 30 | gohook.UnHookMethod(bt, "BufioWriterWriteString") 31 | } 32 | -------------------------------------------------------------------------------- /core/base/bufioWriterWriteString/replacement.go: -------------------------------------------------------------------------------- 1 | package bufioWriterWriteString 2 | 3 | import ( 4 | "bufio" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/utils" 7 | ) 8 | 9 | func WriteString(b *bufio.Writer, v string) (n int, err error) { 10 | if utils.IsHook("net/http.extraHeader.Write", 6) { 11 | value, ok := global.ResponseHeaderMap.Load(utils.CatGoroutineID()) 12 | if ok { 13 | str := utils.StringAdd(value.(string), string(v)) 14 | global.ResponseHeaderMap.Store(utils.CatGoroutineID(), str) 15 | } else { 16 | global.ResponseHeaderMap.Store(utils.CatGoroutineID(), string(v)) 17 | } 18 | } 19 | //request.FmtHookPool(request.PoolReq{ 20 | // Args: request.Collect(argStr, s), 21 | // Reqs: request.Collect(b.String()), 22 | // NeedHook: request.Collect(argStr, s), 23 | // NeedCatch: request.Collect(b.String()), 24 | // Source: false, 25 | // OriginClassName: "bytes.(*Buffer)", 26 | // MethodName: "WriteString", 27 | // ClassName: "bytes.(*Buffer)", 28 | //}) 29 | return WriteStringT(b, v) 30 | } 31 | 32 | func WriteStringT(b *bufio.Writer, v string) (n int, err error) { 33 | return n, err 34 | } 35 | -------------------------------------------------------------------------------- /core/base/builderWriteString/install.go: -------------------------------------------------------------------------------- 1 | package builderWriteString 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["builderWriteString"] = new(BuilderWriteString) 13 | } 14 | 15 | type BuilderWriteString struct { 16 | } 17 | 18 | func (h *BuilderWriteString) Hook() { 19 | var bt strings.Builder 20 | err := gohook.HookMethod(bt, "WriteString", WriteString, WriteStringT) 21 | if err != nil { 22 | fmt.Println(err, "BuilderWriteString") 23 | } else { 24 | fmt.Println("BuilderWriteString") 25 | } 26 | } 27 | 28 | func (h *BuilderWriteString) UnHook() { 29 | var bt bytes.Buffer 30 | gohook.UnHookMethod(bt, "WriteString") 31 | } 32 | -------------------------------------------------------------------------------- /core/base/builderWriteString/replacement.go: -------------------------------------------------------------------------------- 1 | package builderWriteString 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "strings" 6 | ) 7 | 8 | func WriteString(b *strings.Builder, s string) (n int, err error) { 9 | argStr := b.String() 10 | n, err = WriteStringT(b, s) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(argStr, s), 13 | Reqs: request.Collect(b.String()), 14 | Source: false, 15 | OriginClassName: "strings.(*Builder)", 16 | MethodName: "WriteString", 17 | ClassName: "strings.(*Builder)", 18 | }) 19 | return n, err 20 | } 21 | 22 | func WriteStringT(b *strings.Builder, s string) (n int, err error) { 23 | return n, err 24 | } 25 | -------------------------------------------------------------------------------- /core/base/execCmdStart/install.go: -------------------------------------------------------------------------------- 1 | package execCmdStart 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "os/exec" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["execCmdStart"] = new(ExecCmdStart) 12 | } 13 | 14 | type ExecCmdStart struct { 15 | } 16 | 17 | func (h *ExecCmdStart) Hook() { 18 | var cmd *exec.Cmd 19 | err := gohook.HookMethod(cmd, "Start", Start, StartT) 20 | if err != nil { 21 | fmt.Println(err, "execCmdStart") 22 | } else { 23 | fmt.Println("execCmdStart") 24 | } 25 | } 26 | 27 | func (h *ExecCmdStart) UnHook() { 28 | gohook.UnHook(exec.Command) 29 | } 30 | -------------------------------------------------------------------------------- /core/base/execCmdStart/replacement.go: -------------------------------------------------------------------------------- 1 | package execCmdStart 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "os/exec" 6 | "reflect" 7 | ) 8 | 9 | func Start(cmd *exec.Cmd) error { 10 | e := StartT(cmd) 11 | // 12 | var u uintptr 13 | value := reflect.ValueOf(cmd) 14 | u = value.Pointer() 15 | request.FmtHookPool(request.PoolReq{ 16 | Args: request.Collect(cmd.Args), 17 | Reqs: request.Collect(e), 18 | NeedHook: request.Collect(u), 19 | Source: false, 20 | OriginClassName: "exec.(*Cmd)", 21 | MethodName: "Start", 22 | ClassName: "exec.(*Cmd)", 23 | }) 24 | return e 25 | } 26 | 27 | func StartT(cmd *exec.Cmd) error { 28 | return nil 29 | } 30 | -------------------------------------------------------------------------------- /core/base/execCommand/install.go: -------------------------------------------------------------------------------- 1 | package execCommand 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "os/exec" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["execCommand"] = new(ExecCommand) 12 | } 13 | 14 | type ExecCommand struct { 15 | } 16 | 17 | func (h *ExecCommand) Hook() { 18 | err := gohook.Hook(exec.Command, Command, CommandTemp) 19 | if err != nil { 20 | fmt.Println(err, "ExecCommand") 21 | } else { 22 | fmt.Println("ExecCommand") 23 | } 24 | } 25 | 26 | func (h *ExecCommand) UnHook() { 27 | gohook.UnHook(exec.Command) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/execCommand/replacement.go: -------------------------------------------------------------------------------- 1 | package execCommand 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "os/exec" 6 | "reflect" 7 | ) 8 | 9 | func Command(name string, arg ...string) *exec.Cmd { 10 | e := CommandTemp(name, arg...) 11 | // 12 | var u uintptr 13 | value := reflect.ValueOf(e) 14 | u = value.Pointer() 15 | request.FmtHookPool(request.PoolReq{ 16 | Args: request.Collect(name, arg), 17 | Reqs: request.Collect(e), 18 | NeedCatch: request.Collect(u), 19 | Source: false, 20 | OriginClassName: "exec", 21 | MethodName: "Command", 22 | ClassName: "exec", 23 | }) 24 | return e 25 | } 26 | 27 | func CommandTemp(name string, arg ...string) *exec.Cmd { 28 | return &exec.Cmd{} 29 | } 30 | -------------------------------------------------------------------------------- /core/base/fmtSprintf/install.go: -------------------------------------------------------------------------------- 1 | package fmtSprintf 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["fmtSprintf"] = new(FmtSprintf) 11 | } 12 | 13 | type FmtSprintf struct { 14 | } 15 | 16 | func (h *FmtSprintf) Hook() { 17 | err := gohook.Hook(fmt.Sprintf, Sprintf, SprintfT) 18 | if err != nil { 19 | fmt.Println(err, "Sprintf") 20 | } else { 21 | fmt.Println("Sprintf") 22 | } 23 | } 24 | 25 | func (h *FmtSprintf) UnHook() { 26 | gohook.UnHook(fmt.Sprintf) 27 | } 28 | -------------------------------------------------------------------------------- /core/base/fmtSprintf/replacement.go: -------------------------------------------------------------------------------- 1 | package fmtSprintf 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | ) 6 | 7 | func Sprintf(format string, a ...interface{}) string { 8 | s := SprintfT(format, a...) 9 | request.FmtHookPool(request.PoolReq{ 10 | Args: request.Collect(format, a), 11 | Reqs: request.Collect(s), 12 | Source: false, 13 | OriginClassName: "fmt", 14 | MethodName: "Sprintf", 15 | ClassName: "fmt", 16 | }) 17 | return s 18 | } 19 | 20 | func SprintfT(format string, a ...interface{}) string { 21 | return "" 22 | } 23 | -------------------------------------------------------------------------------- /core/base/htmlTemplateExecuteTemplate/install.go: -------------------------------------------------------------------------------- 1 | package htmlTemplateExecuteTemplate 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "html/template" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["htmlTemplateExecuteTemplate"] = new(HtmlTemplateExecuteTemplate) 12 | } 13 | 14 | type HtmlTemplateExecuteTemplate struct { 15 | } 16 | 17 | func (h *HtmlTemplateExecuteTemplate) Hook() { 18 | t := &template.Template{} 19 | err := gohook.HookMethod(t, "ExecuteTemplate", ExecuteTemplate, ExecuteTemplateT) 20 | if err != nil { 21 | fmt.Println(err, "HtmlTemplateExecuteTemplate") 22 | } else { 23 | fmt.Println("HtmlTemplateExecuteTemplate") 24 | } 25 | } 26 | 27 | func (h *HtmlTemplateExecuteTemplate) UnHook() { 28 | t := &template.Template{} 29 | gohook.UnHookMethod(t, "ExecuteTemplate") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/htmlTemplateExecuteTemplate/replacement.go: -------------------------------------------------------------------------------- 1 | package htmlTemplateExecuteTemplate 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "html/template" 6 | "io" 7 | ) 8 | 9 | func ExecuteTemplate(template *template.Template, wr io.Writer, name string, data interface{}) error { 10 | err := ExecuteTemplateT(template, wr, name, data) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(wr, name, data), 13 | Reqs: request.Collect(err), 14 | Source: false, 15 | OriginClassName: "template.(*Template)", 16 | MethodName: "ExecuteTemplate", 17 | ClassName: "template.(*Template)", 18 | }) 19 | return err 20 | } 21 | 22 | func ExecuteTemplateT(template *template.Template, wr io.Writer, name string, data interface{}) error { 23 | return nil 24 | } 25 | -------------------------------------------------------------------------------- /core/base/httpClientDo/install.go: -------------------------------------------------------------------------------- 1 | package httpClientDo 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpClientDo"] = new(HttpClientDo) 12 | } 13 | 14 | type HttpClientDo struct { 15 | } 16 | 17 | func (h *HttpClientDo) Hook() { 18 | client := &http.Client{} 19 | err := gohook.HookMethod(client, "Do", Do, DoR) 20 | if err != nil { 21 | fmt.Println(err, "HttpClientDo") 22 | } else { 23 | fmt.Println("HttpClientDo") 24 | } 25 | } 26 | 27 | func (h *HttpClientDo) UnHook() { 28 | client := &http.Client{} 29 | gohook.UnHookMethod(client, "Do") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/httpClientDo/replacement.go: -------------------------------------------------------------------------------- 1 | package httpClientDo 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "net/http" 6 | "reflect" 7 | ) 8 | 9 | func Do(c *http.Client, req *http.Request) (*http.Response, error) { 10 | res, err := DoR(c, req) 11 | var u uintptr 12 | value := reflect.ValueOf(req) 13 | u = value.Pointer() 14 | request.FmtHookPool(request.PoolReq{ 15 | Args: request.Collect(c, req), 16 | Reqs: request.Collect(res, err), 17 | NeedHook: request.Collect(u), 18 | Source: false, 19 | OriginClassName: "http.(*Client)", 20 | MethodName: "Do", 21 | ClassName: "http.(*Client)", 22 | }) 23 | return res, err 24 | } 25 | 26 | func DoR(c *http.Client, req *http.Request) (*http.Response, error) { 27 | return nil, nil 28 | } 29 | -------------------------------------------------------------------------------- /core/base/httpNewRequest/install.go: -------------------------------------------------------------------------------- 1 | package httpNewRequest 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpNewRequest"] = new(HttpNewRequest) 12 | } 13 | 14 | type HttpNewRequest struct { 15 | } 16 | 17 | func (h *HttpNewRequest) Hook() { 18 | err := gohook.Hook(http.NewRequest, NewRequest, NewRequestR) 19 | if err != nil { 20 | fmt.Println(err, "HttpNewRequest") 21 | } else { 22 | fmt.Println("HttpNewRequest") 23 | } 24 | } 25 | 26 | func (h *HttpNewRequest) UnHook() { 27 | gohook.UnHook(http.NewRequest) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/httpNewRequest/replacement.go: -------------------------------------------------------------------------------- 1 | package httpNewRequest 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "io" 6 | "net/http" 7 | "reflect" 8 | ) 9 | 10 | func NewRequest(method, url string, body io.Reader) (*http.Request, error) { 11 | req, err := NewRequestR(method, url, body) 12 | var u uintptr 13 | value := reflect.ValueOf(req) 14 | u = value.Pointer() 15 | request.FmtHookPool(request.PoolReq{ 16 | Args: request.Collect(method, url, body), 17 | Reqs: request.Collect(req, err), 18 | NeedCatch: request.Collect(u), 19 | Source: false, 20 | OriginClassName: "http", 21 | MethodName: "NewRequest", 22 | ClassName: "http", 23 | }) 24 | return req, err 25 | } 26 | 27 | func NewRequestR(method, url string, body io.Reader) (*http.Request, error) { 28 | return nil, nil 29 | } 30 | -------------------------------------------------------------------------------- /core/base/ioReadAll/install.go: -------------------------------------------------------------------------------- 1 | package ioReadAll 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "io" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ioReadAll"] = new(IoReadAll) 12 | } 13 | 14 | type IoReadAll struct { 15 | } 16 | 17 | func (h *IoReadAll) Hook() { 18 | err := gohook.Hook(io.ReadAll, ReadAll, ReadAllT) 19 | if err != nil { 20 | fmt.Println(err, "IoReadAll") 21 | } else { 22 | fmt.Println("IoReadAll") 23 | } 24 | } 25 | 26 | func (h *IoReadAll) UnHook() { 27 | gohook.UnHook(io.ReadAll) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/ioReadAll/replacement.go: -------------------------------------------------------------------------------- 1 | package ioReadAll 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/pkg/errors" 6 | "io" 7 | "reflect" 8 | ) 9 | 10 | func ReadAll(r io.Reader) ([]byte, error) { 11 | 12 | v := reflect.ValueOf(r) 13 | b, e := ReadAllT(r) 14 | var u uintptr 15 | value := reflect.ValueOf(b) 16 | u = value.Pointer() 17 | request.FmtHookPool(request.PoolReq{ 18 | Args: request.Collect(r), 19 | Reqs: request.Collect(b, e), 20 | NeedCatch: request.Collect(u), 21 | Source: v.Type().String() == "*http.body", 22 | OriginClassName: "io", 23 | MethodName: "ReadAll", 24 | ClassName: "io", 25 | }) 26 | return b, e 27 | } 28 | 29 | func ReadAllT(r io.Reader) ([]byte, error) { 30 | return []byte{}, errors.New("") 31 | } 32 | -------------------------------------------------------------------------------- /core/base/jsonDecoderDecode/install.go: -------------------------------------------------------------------------------- 1 | package jsonDecoderDecode 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["jsonDecoderDecode"] = new(JsonDecoderDecode) 12 | } 13 | 14 | type JsonDecoderDecode struct { 15 | } 16 | 17 | func (h *JsonDecoderDecode) Hook() { 18 | d := &json.Decoder{} 19 | err := gohook.HookMethod(d, "Decode", Decode, DecodeT) 20 | if err != nil { 21 | fmt.Println(err, "JsonDecoderDecode") 22 | } else { 23 | fmt.Println("JsonDecoderDecode") 24 | } 25 | } 26 | 27 | func (h *JsonDecoderDecode) UnHook() { 28 | d := &json.Decoder{} 29 | gohook.UnHookMethod(d, "JsonDecoderDecode") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/jsonDecoderDecode/replacement.go: -------------------------------------------------------------------------------- 1 | package jsonDecoderDecode 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/HXSecurity/DongTai-agent-go/model/request" 6 | "reflect" 7 | ) 8 | 9 | func Decode(decoder *json.Decoder, v interface{}) error { 10 | var u uintptr 11 | value := reflect.ValueOf(decoder) 12 | u = value.Pointer() 13 | e := DecodeT(decoder, v) 14 | request.FmtHookPool(request.PoolReq{ 15 | Args: request.Collect(decoder), 16 | Reqs: request.Collect(v), 17 | NeedHook: request.Collect(u), 18 | Source: false, 19 | OriginClassName: "json.(*Decoder)", 20 | MethodName: "Decode", 21 | ClassName: "json.(*Decoder)", 22 | }) 23 | return e 24 | } 25 | 26 | func DecodeT(decoder *json.Decoder, v interface{}) error { 27 | return nil 28 | } 29 | -------------------------------------------------------------------------------- /core/base/jsonNewDecoder/install.go: -------------------------------------------------------------------------------- 1 | package jsonNewDecoder 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["jsonNewDecoder"] = new(JsonNewDecoder) 12 | } 13 | 14 | type JsonNewDecoder struct { 15 | } 16 | 17 | func (h *JsonNewDecoder) Hook() { 18 | err := gohook.Hook(json.NewDecoder, NewDecoder, NewDecoderT) 19 | if err != nil { 20 | fmt.Println(err, "JsonNewDecoder") 21 | } else { 22 | fmt.Println("JsonNewDecoder") 23 | } 24 | } 25 | 26 | func (h *JsonNewDecoder) UnHook() { 27 | gohook.UnHook(json.NewDecoder) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/jsonNewDecoder/replacement.go: -------------------------------------------------------------------------------- 1 | package jsonNewDecoder 2 | 3 | import ( 4 | "encoding/json" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/HXSecurity/DongTai-agent-go/model/request" 7 | "io" 8 | "reflect" 9 | ) 10 | 11 | func NewDecoder(r io.Reader) *json.Decoder { 12 | v := reflect.ValueOf(r) 13 | d := NewDecoderT(r) 14 | var u uintptr 15 | value := reflect.ValueOf(d) 16 | u = value.Pointer() 17 | request.FmtHookPool(request.PoolReq{ 18 | Args: request.Collect(r), 19 | Reqs: request.Collect(d), 20 | NeedCatch: request.Collect(u), 21 | Source: v.Type().String() == "*http.body" && model.HookMap["ginEngineServerHTTP"] == nil, 22 | OriginClassName: "json", 23 | MethodName: "NewDecoder", 24 | ClassName: "json", 25 | }) 26 | return d 27 | } 28 | 29 | func NewDecoderT(r io.Reader) (d *json.Decoder) { 30 | return 31 | } 32 | -------------------------------------------------------------------------------- /core/base/jsonUnmarshal/install.go: -------------------------------------------------------------------------------- 1 | package jsonUnmarshal 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["jsonUnmarshal"] = new(JsonUnmarshal) 12 | } 13 | 14 | type JsonUnmarshal struct { 15 | } 16 | 17 | func (h *JsonUnmarshal) Hook() { 18 | err := gohook.Hook(json.Unmarshal, Unmarshal, UnmarshalT) 19 | if err != nil { 20 | fmt.Println(err, "JsonUnmarshal") 21 | } else { 22 | fmt.Println("JsonUnmarshal") 23 | } 24 | } 25 | 26 | func (h *JsonUnmarshal) UnHook() { 27 | gohook.UnHook(json.Unmarshal) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/jsonUnmarshal/replacement.go: -------------------------------------------------------------------------------- 1 | package jsonUnmarshal 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "reflect" 6 | ) 7 | 8 | func Unmarshal(data []byte, v interface{}) error { 9 | 10 | var u uintptr 11 | value := reflect.ValueOf(data) 12 | u = value.Pointer() 13 | e := UnmarshalT(data, v) 14 | request.FmtHookPool(request.PoolReq{ 15 | Args: request.Collect(data), 16 | Reqs: request.Collect(v), 17 | NeedHook: request.Collect(u), 18 | Source: false, 19 | OriginClassName: "json", 20 | MethodName: "Unmarshal", 21 | ClassName: "json", 22 | }) 23 | return e 24 | } 25 | 26 | func UnmarshalT(data []byte, v interface{}) error { 27 | return nil 28 | } 29 | -------------------------------------------------------------------------------- /core/base/osOpenFile/install.go: -------------------------------------------------------------------------------- 1 | package osOpenFile 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "os" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["osOpenFile"] = new(OsOpenFile) 12 | } 13 | 14 | type OsOpenFile struct { 15 | } 16 | 17 | func (h *OsOpenFile) Hook() { 18 | err := gohook.Hook(os.OpenFile, OpenFile, OpenFileT) 19 | if err != nil { 20 | fmt.Println(err, "OsOpenFile") 21 | } else { 22 | fmt.Println("OsOpenFile") 23 | } 24 | } 25 | 26 | func (h *OsOpenFile) UnHook() { 27 | gohook.UnHook(os.OpenFile) 28 | } 29 | -------------------------------------------------------------------------------- /core/base/osOpenFile/replacement.go: -------------------------------------------------------------------------------- 1 | package osOpenFile 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "os" 6 | ) 7 | 8 | func OpenFile(name string, flag int, perm os.FileMode) (*os.File, error) { 9 | f, e := OpenFileT(name, flag, perm) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(name, flag, perm), 12 | Reqs: request.Collect(f, e), 13 | Source: false, 14 | OriginClassName: "os", 15 | MethodName: "OpenFile", 16 | ClassName: "os", 17 | }) 18 | return f, e 19 | } 20 | 21 | func OpenFileT(name string, flag int, perm os.FileMode) (*os.File, error) { 22 | return nil, nil 23 | } 24 | -------------------------------------------------------------------------------- /core/base/regexpRegexpReplaceAllString/install.go: -------------------------------------------------------------------------------- 1 | package regexpRegexpReplaceAllString 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "regexp" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["regexpRegexpReplaceAllString"] = new(RegexpRegexpReplaceAllString) 12 | } 13 | 14 | type RegexpRegexpReplaceAllString struct { 15 | } 16 | 17 | func (h *RegexpRegexpReplaceAllString) Hook() { 18 | var r *regexp.Regexp 19 | err := gohook.HookMethod(r, "ReplaceAllString", ReplaceAllString, ReplaceAllStringT) 20 | if err != nil { 21 | fmt.Println(err, "RegexpRegexpReplaceAllString") 22 | } else { 23 | fmt.Println("RegexpRegexpReplaceAllString") 24 | } 25 | } 26 | 27 | func (h *RegexpRegexpReplaceAllString) UnHook() { 28 | var r *regexp.Regexp 29 | err := gohook.UnHookMethod(r, "ReplaceAllString") 30 | if err != nil { 31 | fmt.Println(err, "RegexpRegexpReplaceAllString") 32 | } else { 33 | fmt.Println("RegexpRegexpReplaceAllString") 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /core/base/regexpRegexpReplaceAllString/replacement.go: -------------------------------------------------------------------------------- 1 | package regexpRegexpReplaceAllString 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "regexp" 6 | ) 7 | 8 | func ReplaceAllString(re *regexp.Regexp, src, repl string) string { 9 | s := ReplaceAllStringT(re, src, repl) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(src, repl), 12 | Reqs: request.Collect(s), 13 | Source: false, 14 | OriginClassName: "regexp.(*Regexp)", 15 | MethodName: "ReplaceAllString", 16 | ClassName: "regexp.(*Regexp)", 17 | }) 18 | return s 19 | } 20 | 21 | func ReplaceAllStringT(re *regexp.Regexp, src, repl string) string { 22 | return "" 23 | } 24 | -------------------------------------------------------------------------------- /core/base/runtimeConcatstrings/empty.s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-go/5a20e93ff596eaec15606edf8138c52eb1446c21/core/base/runtimeConcatstrings/empty.s -------------------------------------------------------------------------------- /core/base/runtimeConcatstrings/install.go: -------------------------------------------------------------------------------- 1 | package runtimeConcatstrings 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["runtimeConcatstrings"] = new(RuntimeConcatstrings) 11 | } 12 | 13 | type RuntimeConcatstrings struct { 14 | } 15 | 16 | func (h *RuntimeConcatstrings) Hook() { 17 | err := gohook.Hook(concatstrings, concatstringsR, concatstringsT) 18 | if err != nil { 19 | fmt.Println(err, "RuntimeConcatstrings") 20 | } else { 21 | fmt.Println("RuntimeConcatstrings") 22 | } 23 | } 24 | 25 | func (h *RuntimeConcatstrings) UnHook() { 26 | gohook.UnHook(concatstrings) 27 | } 28 | -------------------------------------------------------------------------------- /core/base/runtimeConcatstrings/replacement.go: -------------------------------------------------------------------------------- 1 | package runtimeConcatstrings 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/HXSecurity/DongTai-agent-go/utils" 6 | _ "unsafe" 7 | ) 8 | 9 | const tmpStringBufSize = 32 10 | 11 | type tmpBuf [tmpStringBufSize]byte 12 | 13 | //go:linkname concatstrings runtime.concatstrings 14 | func concatstrings(buf *tmpBuf, a []string) string 15 | 16 | func concatstringsR(buf *tmpBuf, a []string) string { 17 | e := concatstringsT(buf, a) 18 | var WriteMap = make(map[string]bool) 19 | WriteMap["github.com/HXSecurity/DongTai-agent-go/core/httpRouter/httpRouter.MyHttpRouterServer.func1"] = true 20 | WriteMap["os.openDir"] = true 21 | WriteMap["io/fs.(*PathError).Error"] = true 22 | WriteMap["syscall.UTF16FromString"] = true 23 | WriteMap["os/exec.findExecutable"] = true 24 | if !WriteMap[utils.LoadFunc(3)] { 25 | var ArgStr = "[" 26 | for k, v := range a { 27 | ArgStr = utils.StringAdd(ArgStr, v) 28 | if k != len(a)-1 { 29 | ArgStr = utils.StringAdd(ArgStr, ",") 30 | } else { 31 | ArgStr = utils.StringAdd(ArgStr, "]") 32 | } 33 | } 34 | NeedHook := make([]interface{}, len(a)) 35 | for i, v := range a { 36 | NeedHook[i] = v 37 | } 38 | request.FmtHookPool(request.PoolReq{ 39 | Args: request.Collect(a), 40 | ArgsStr: ArgStr, 41 | Reqs: request.Collect(e), 42 | NeedHook: NeedHook, 43 | NeedCatch: request.Collect(e), 44 | Source: false, 45 | OriginClassName: "runtime", 46 | MethodName: "concatstrings", 47 | ClassName: "runtime", 48 | }) 49 | } 50 | return e 51 | } 52 | 53 | func concatstringsT(buf *tmpBuf, a []string) string { 54 | return "" 55 | } 56 | -------------------------------------------------------------------------------- /core/base/runtimeMapassign_faststr/empty.s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-go/5a20e93ff596eaec15606edf8138c52eb1446c21/core/base/runtimeMapassign_faststr/empty.s -------------------------------------------------------------------------------- /core/base/runtimeMapassign_faststr/install.go: -------------------------------------------------------------------------------- 1 | package runtimeMapassign_faststr 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["runtimeConcatstrings"] = new(RuntimeMapassign_faststr) 11 | } 12 | 13 | type RuntimeMapassign_faststr struct { 14 | } 15 | 16 | func (h *RuntimeMapassign_faststr) Hook() { 17 | err := gohook.Hook(mapassign_faststr, mapassign_faststrR, mapassign_faststrT) 18 | if err != nil { 19 | fmt.Println(err, "RuntimeMapassign_faststr") 20 | } else { 21 | fmt.Println("RuntimeMapassign_faststr") 22 | } 23 | } 24 | 25 | func (h *RuntimeMapassign_faststr) UnHook() { 26 | gohook.UnHook(mapassign_faststr) 27 | } 28 | -------------------------------------------------------------------------------- /core/base/runtimeMapassign_faststr/replacement.go: -------------------------------------------------------------------------------- 1 | package runtimeMapassign_faststr 2 | 3 | import ( 4 | "fmt" 5 | "unsafe" 6 | _ "unsafe" 7 | ) 8 | 9 | const tmpStringBufSize = 32 10 | 11 | type tflag uint8 12 | type nameOff int32 13 | type typeOff int32 14 | 15 | type _type struct { 16 | size uintptr 17 | ptrdata uintptr // size of memory prefix holding all pointers 18 | hash uint32 19 | tflag tflag 20 | align uint8 21 | fieldAlign uint8 22 | kind uint8 23 | // function for comparing objects of this type 24 | // (ptr to object A, ptr to object B) -> ==? 25 | equal func(unsafe.Pointer, unsafe.Pointer) bool 26 | // gcdata stores the GC type data for the garbage collector. 27 | // If the KindGCProg bit is set in kind, gcdata is a GC program. 28 | // Otherwise it is a ptrmask bitmap. See mbitmap.go for details. 29 | gcdata *byte 30 | str nameOff 31 | ptrToThis typeOff 32 | } 33 | 34 | type maptype struct { 35 | typ _type 36 | key *_type 37 | elem *_type 38 | bucket *_type // internal type representing a hash bucket 39 | // function for hashing keys (ptr to key, seed) -> hash 40 | hasher func(unsafe.Pointer, uintptr) uintptr 41 | keysize uint8 // size of key slot 42 | elemsize uint8 // size of elem slot 43 | bucketsize uint16 // size of bucket 44 | flags uint32 45 | } 46 | 47 | // A header for a Go map. 48 | type hmap struct { 49 | // Note: the format of the hmap is also encoded in cmd/compile/internal/reflectdata/reflect.go. 50 | // Make sure this stays in sync with the compiler's definition. 51 | count int // # live cells == size of map. Must be first (used by len() builtin) 52 | flags uint8 53 | B uint8 // log_2 of # of buckets (can hold up to loadFactor * 2^B items) 54 | noverflow uint16 // approximate number of overflow buckets; see incrnoverflow for details 55 | hash0 uint32 // hash seed 56 | 57 | buckets unsafe.Pointer // array of 2^B Buckets. may be nil if count==0. 58 | oldbuckets unsafe.Pointer // previous bucket array of half the size, non-nil only when growing 59 | nevacuate uintptr // progress counter for evacuation (buckets less than this have been evacuated) 60 | 61 | extra *mapextra // optional fields 62 | } 63 | 64 | const ( 65 | // Maximum number of key/elem pairs a bucket can hold. 66 | bucketCntBits = 3 67 | bucketCnt = 1 << bucketCntBits 68 | ) 69 | 70 | // A bucket for a Go map. 71 | type bmap struct { 72 | // tophash generally contains the top byte of the hash value 73 | // for each key in this bucket. If tophash[0] < minTopHash, 74 | // tophash[0] is a bucket evacuation state instead. 75 | tophash [bucketCnt]uint8 76 | // Followed by bucketCnt keys and then bucketCnt elems. 77 | // NOTE: packing all the keys together and then all the elems together makes the 78 | // code a bit more complicated than alternating key/elem/key/elem/... but it allows 79 | // us to eliminate padding which would be needed for, e.g., map[int64]int8. 80 | // Followed by an overflow pointer. 81 | } 82 | 83 | // mapextra holds fields that are not present on all maps. 84 | type mapextra struct { 85 | // If both key and elem do not contain pointers and are inline, then we mark bucket 86 | // type as containing no pointers. This avoids scanning such maps. 87 | // However, bmap.overflow is a pointer. In order to keep overflow buckets 88 | // alive, we store pointers to all overflow buckets in hmap.extra.overflow and hmap.extra.oldoverflow. 89 | // overflow and oldoverflow are only used if key and elem do not contain pointers. 90 | // overflow contains overflow buckets for hmap.buckets. 91 | // oldoverflow contains overflow buckets for hmap.oldbuckets. 92 | // The indirection allows to store a pointer to the slice in hiter. 93 | overflow *[]*bmap 94 | oldoverflow *[]*bmap 95 | 96 | // nextOverflow holds a pointer to a free overflow bucket. 97 | nextOverflow *bmap 98 | } 99 | 100 | //go:linkname concatstrings runtime.mapassign_faststr 101 | func mapassign_faststr(t *maptype, h *hmap, s string) unsafe.Pointer 102 | 103 | func mapassign_faststrR(t *maptype, h *hmap, s string) unsafe.Pointer { 104 | fmt.Println("Hook到了mapassign_faststrR方法") 105 | fmt.Println("入参为", t, h, s) 106 | e := mapassign_faststrT(t, h, s) 107 | fmt.Println("返回值", e) 108 | return e 109 | } 110 | 111 | func mapassign_faststrT(t *maptype, h *hmap, s string) unsafe.Pointer { 112 | return *new(unsafe.Pointer) 113 | } 114 | -------------------------------------------------------------------------------- /core/base/runtimeSlicebytetostring/empty.s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-go/5a20e93ff596eaec15606edf8138c52eb1446c21/core/base/runtimeSlicebytetostring/empty.s -------------------------------------------------------------------------------- /core/base/runtimeSlicebytetostring/install.go: -------------------------------------------------------------------------------- 1 | package runtimeSlicebytetostring 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model" 5 | "github.com/brahma-adshonor/gohook" 6 | ) 7 | 8 | func init() { 9 | model.HookMap["runtimeSlicebytetostring"] = new(RuntimeSlicebytetostring) 10 | } 11 | 12 | type RuntimeSlicebytetostring struct { 13 | } 14 | 15 | func (h *RuntimeSlicebytetostring) Hook() { 16 | gohook.Hook(slicebytetostring, slicebytetostringR, slicebytetostringT) 17 | } 18 | 19 | func (h *RuntimeSlicebytetostring) UnHook() { 20 | gohook.UnHook(slicebytetostring) 21 | } 22 | -------------------------------------------------------------------------------- /core/base/runtimeSlicebytetostring/replacement.go: -------------------------------------------------------------------------------- 1 | package runtimeSlicebytetostring 2 | 3 | import ( 4 | _ "unsafe" 5 | ) 6 | 7 | const tmpStringBufSize = 32 8 | 9 | type tmpBuf [tmpStringBufSize]byte 10 | 11 | var staticuint64s = [...]uint64{ 12 | 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 13 | 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 14 | 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 15 | 0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 16 | 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 17 | 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 18 | 0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 19 | 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 20 | 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 21 | 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f, 22 | 0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57, 23 | 0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f, 24 | 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 25 | 0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f, 26 | 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 27 | 0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f, 28 | 0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 29 | 0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 30 | 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 31 | 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f, 32 | 0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7, 33 | 0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf, 34 | 0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7, 35 | 0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf, 36 | 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 37 | 0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf, 38 | 0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 39 | 0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf, 40 | 0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 41 | 0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef, 42 | 0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 43 | 0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff, 44 | } 45 | 46 | //go:linkname slicebytetostring runtime.slicebytetostring 47 | func slicebytetostring(buf *tmpBuf, ptr *byte, n int) (str string) 48 | 49 | func slicebytetostringR(buf *tmpBuf, ptr *byte, n int) (str string) { 50 | e := slicebytetostringT(buf, ptr, n) 51 | //fmt.Println("返回值", e) 52 | return e 53 | } 54 | 55 | func slicebytetostringT(buf *tmpBuf, ptr *byte, n int) (str string) { 56 | return "" 57 | } 58 | -------------------------------------------------------------------------------- /core/base/runtimesSringtoslicebyte/empty.s: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/HXSecurity/DongTai-agent-go/5a20e93ff596eaec15606edf8138c52eb1446c21/core/base/runtimesSringtoslicebyte/empty.s -------------------------------------------------------------------------------- /core/base/runtimesSringtoslicebyte/install.go: -------------------------------------------------------------------------------- 1 | package runtimesSringtoslicebyte 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["runtimesSringtoslicebyte"] = new(RuntimesSringtoslicebyte) 11 | } 12 | 13 | type RuntimesSringtoslicebyte struct { 14 | } 15 | 16 | func (h *RuntimesSringtoslicebyte) Hook() { 17 | err := gohook.Hook(stringtoslicebyte, stringtoslicebyteR, stringtoslicebyteT) 18 | if err != nil { 19 | fmt.Println("RuntimesSringtoslicebyte:", err) 20 | } else { 21 | fmt.Println("RuntimesSringtoslicebyte") 22 | } 23 | } 24 | 25 | func (h *RuntimesSringtoslicebyte) UnHook() { 26 | err := gohook.UnHook(stringtoslicebyte) 27 | if err != nil { 28 | fmt.Println("RuntimesSringtoslicebyte:", err) 29 | } else { 30 | fmt.Println("RuntimesSringtoslicebyte") 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /core/base/runtimesSringtoslicebyte/replacement.go: -------------------------------------------------------------------------------- 1 | package runtimesSringtoslicebyte 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "reflect" 6 | _ "unsafe" 7 | ) 8 | 9 | const tmpStringBufSize = 32 10 | 11 | type tmpBuf [tmpStringBufSize]byte 12 | 13 | //go:linkname stringtoslicebyte runtime.stringtoslicebyte 14 | func stringtoslicebyte(buf *tmpBuf, s string) []byte 15 | 16 | func stringtoslicebyteR(buf *tmpBuf, s string) []byte { 17 | b := stringtoslicebyteT(buf, s) 18 | 19 | var u uintptr 20 | value := reflect.ValueOf(b) 21 | u = value.Pointer() 22 | request.FmtHookPool(request.PoolReq{ 23 | Args: request.Collect(s), 24 | Reqs: request.Collect(b), 25 | NeedCatch: request.Collect(u), 26 | Source: false, 27 | OriginClassName: "runtime", 28 | MethodName: "stringtoslicebyte", 29 | ClassName: "runtime", 30 | }) 31 | return b 32 | } 33 | 34 | func stringtoslicebyteT(buf *tmpBuf, s string) []byte { 35 | return []byte{} 36 | } 37 | -------------------------------------------------------------------------------- /core/base/sqlDBQuery/install.go: -------------------------------------------------------------------------------- 1 | package sqlDBQuery 2 | 3 | import ( 4 | "database/sql" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["sqlDBQuery"] = new(SqlDBQuery) 12 | } 13 | 14 | type SqlDBQuery struct { 15 | } 16 | 17 | func (h *SqlDBQuery) Hook() { 18 | var db *sql.DB 19 | err := gohook.HookMethod(db, "Query", Query, QueryT) 20 | if err != nil { 21 | fmt.Println(err, "SqlDBQuery") 22 | } else { 23 | fmt.Println("SqlDBQuery") 24 | } 25 | } 26 | 27 | func (h *SqlDBQuery) UnHook() { 28 | var db *sql.DB 29 | gohook.UnHookMethod(db, "Query") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/sqlDBQuery/replacement.go: -------------------------------------------------------------------------------- 1 | package sqlDBQuery 2 | 3 | import ( 4 | "database/sql" 5 | "github.com/HXSecurity/DongTai-agent-go/model/request" 6 | ) 7 | 8 | func Query(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) { 9 | rows, sql := QueryT(db, query, args...) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(query, args), 12 | Reqs: request.Collect(rows, sql), 13 | Source: false, 14 | OriginClassName: "sql.(*DB)", 15 | MethodName: "Query", 16 | ClassName: "sql.(*DB)", 17 | }) 18 | 19 | return rows, sql 20 | } 21 | 22 | func QueryT(db *sql.DB, query string, args ...interface{}) (*sql.Rows, error) { 23 | return nil, nil 24 | } 25 | -------------------------------------------------------------------------------- /core/base/stringsBuilderWriteString/install.go: -------------------------------------------------------------------------------- 1 | package stringsBuilderWriteString 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | "strings" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["stringsBuilderWriteString"] = new(BufferWriteString) 13 | } 14 | 15 | type BufferWriteString struct { 16 | } 17 | 18 | func (h *BufferWriteString) Hook() { 19 | var bt *strings.Builder 20 | err := gohook.HookMethod(bt, "WriteString", WriteString, WriteStringT) 21 | if err != nil { 22 | fmt.Println(err, "stringsBuilderWriteString") 23 | } else { 24 | fmt.Println("stringsBuilderWriteString") 25 | } 26 | } 27 | 28 | func (h *BufferWriteString) UnHook() { 29 | var bt bytes.Buffer 30 | gohook.UnHookMethod(bt, "stringsBuilderWriteString") 31 | } 32 | -------------------------------------------------------------------------------- /core/base/stringsBuilderWriteString/replacement.go: -------------------------------------------------------------------------------- 1 | package stringsBuilderWriteString 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/HXSecurity/DongTai-agent-go/utils" 6 | "strings" 7 | ) 8 | 9 | func WriteString(b *strings.Builder, s string) (n int, err error) { 10 | argStr := b.String() 11 | n, err = WriteStringT(b, s) 12 | var WriteMap = make(map[string]bool) 13 | WriteMap["strings.Join"] = true 14 | WriteMap["strings.Replace"] = true 15 | WriteMap["net/url.Values.Encode"] = true 16 | WriteMap["net/url.(*URL).String"] = true 17 | if !WriteMap[utils.LoadFunc(2)] { 18 | request.FmtHookPool(request.PoolReq{ 19 | Args: request.Collect(argStr, s), 20 | Reqs: request.Collect(b.String()), 21 | NeedHook: request.Collect(argStr, s), 22 | NeedCatch: request.Collect(b.String()), 23 | Source: false, 24 | OriginClassName: "strings.(*Builder)", 25 | MethodName: "WriteString", 26 | ClassName: "strings.(*Builder)", 27 | }) 28 | } 29 | return n, err 30 | } 31 | 32 | func WriteStringT(b *strings.Builder, s string) (n int, err error) { 33 | return n, err 34 | } 35 | -------------------------------------------------------------------------------- /core/base/stringsJoin/install.go: -------------------------------------------------------------------------------- 1 | package stringsJoin 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model" 5 | "github.com/brahma-adshonor/gohook" 6 | "strings" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["stringsJoin"] = new(StringsJoin) 11 | } 12 | 13 | type StringsJoin struct { 14 | } 15 | 16 | func (h *StringsJoin) Hook() { 17 | gohook.Hook(strings.Join, Join, JoinT) 18 | } 19 | 20 | func (h *StringsJoin) UnHook() { 21 | gohook.UnHook(strings.Join) 22 | } 23 | -------------------------------------------------------------------------------- /core/base/stringsJoin/replacement.go: -------------------------------------------------------------------------------- 1 | package stringsJoin 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func Join(elems []string, sep string) string { 8 | fmt.Println("hook到方法fmt.Sprintf") 9 | fmt.Println("入参", elems, sep) 10 | s := JoinT(elems, sep) 11 | fmt.Println("回参", s) 12 | return s 13 | } 14 | 15 | func JoinT(elems []string, sep string) string { 16 | return "" 17 | } 18 | -------------------------------------------------------------------------------- /core/base/stringsRepeat/install.go: -------------------------------------------------------------------------------- 1 | package stringsRepeat 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model" 5 | "github.com/brahma-adshonor/gohook" 6 | "strings" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["stringsRepeat"] = new(StringsRepeat) 11 | } 12 | 13 | type StringsRepeat struct { 14 | } 15 | 16 | func (h *StringsRepeat) Hook() { 17 | gohook.Hook(strings.Repeat, Repeat, RepeatR) 18 | } 19 | 20 | func (h *StringsRepeat) UnHook() { 21 | gohook.UnHook(strings.Repeat) 22 | } 23 | -------------------------------------------------------------------------------- /core/base/stringsRepeat/replacement.go: -------------------------------------------------------------------------------- 1 | package stringsRepeat 2 | 3 | func Repeat(s, old, new string, n int) string { 4 | re := RepeatR(s, old, new, n) 5 | return re 6 | } 7 | 8 | func RepeatR(s, old, new string, n int) string { 9 | return "" 10 | } 11 | -------------------------------------------------------------------------------- /core/base/stringsReplace/install.go: -------------------------------------------------------------------------------- 1 | package stringsReplace 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model" 5 | "github.com/brahma-adshonor/gohook" 6 | "strings" 7 | ) 8 | 9 | func init() { 10 | model.HookMap["stringsReplace"] = new(StringsReplace) 11 | } 12 | 13 | type StringsReplace struct { 14 | } 15 | 16 | func (h *StringsReplace) Hook() { 17 | gohook.Hook(strings.Replace, Replace, ReplaceR) 18 | } 19 | 20 | func (h *StringsReplace) UnHook() { 21 | gohook.UnHook(strings.Replace) 22 | } 23 | -------------------------------------------------------------------------------- /core/base/stringsReplace/replacement.go: -------------------------------------------------------------------------------- 1 | package stringsReplace 2 | 3 | func Replace(s, old, new string, n int) string { 4 | re := ReplaceR(s, old, new, n) 5 | return re 6 | } 7 | 8 | func ReplaceR(s, old, new string, n int) string { 9 | return "" 10 | } 11 | -------------------------------------------------------------------------------- /core/base/urlUrlString/install.go: -------------------------------------------------------------------------------- 1 | package urlUrlString 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/url" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["urlUrlString"] = new(UrlUrlString) 12 | } 13 | 14 | type UrlUrlString struct { 15 | } 16 | 17 | func (h *UrlUrlString) Hook() { 18 | var url *url.URL 19 | err := gohook.HookMethod(url, "String", String, StringT) 20 | if err != nil { 21 | fmt.Println(err, "UrlUrlString") 22 | } else { 23 | fmt.Println("UrlUrlString") 24 | } 25 | } 26 | 27 | func (h *UrlUrlString) UnHook() { 28 | var url *url.URL 29 | gohook.UnHookMethod(url, "UrlUrlString") 30 | } 31 | -------------------------------------------------------------------------------- /core/base/urlUrlString/replacement.go: -------------------------------------------------------------------------------- 1 | package urlUrlString 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "net/url" 6 | ) 7 | 8 | func String(url *url.URL) string { 9 | s := StringT(url) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(url), 12 | Reqs: request.Collect(s), 13 | Source: false, 14 | OriginClassName: "url.(*URL)", 15 | MethodName: "String", 16 | ClassName: "url.(*URL)", 17 | }) 18 | 19 | return s 20 | } 21 | 22 | func StringT(url *url.URL) string { 23 | return "" 24 | } 25 | -------------------------------------------------------------------------------- /core/gin/ginContextGetPostFormArray/install.go: -------------------------------------------------------------------------------- 1 | package ginContextGetPostFormArray 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextGetPostFormArray"] = new(GinContextGetPostFormArray) 12 | } 13 | 14 | type GinContextGetPostFormArray struct { 15 | } 16 | 17 | func (h *GinContextGetPostFormArray) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "GetPostFormArray", GetPostFormArray, GetPostFormArrayT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextGetPostFormArray") 22 | } else { 23 | fmt.Println("GinContextGetPostFormArray") 24 | } 25 | } 26 | 27 | func (h *GinContextGetPostFormArray) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "GetPostFormArray") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextGetPostFormArray/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextGetPostFormArray 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func GetPostFormArray(c *gin.Context, key string) ([]string, bool) { 9 | reArray, flag := GetPostFormArrayT(c, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(reArray), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "GetPostFormArray", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return reArray, flag 19 | } 20 | 21 | func GetPostFormArrayT(c *gin.Context, key string) ([]string, bool) { 22 | return []string{}, false 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextGetPostFormMap/install.go: -------------------------------------------------------------------------------- 1 | package ginContextGetPostFormMap 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextGetPostFormMap"] = new(GinContextGetPostFormMap) 12 | } 13 | 14 | type GinContextGetPostFormMap struct { 15 | } 16 | 17 | func (h *GinContextGetPostFormMap) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "GetPostFormMap", GetPostFormMap, GetPostFormMapT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextGetPostFormMap") 22 | } else { 23 | fmt.Println("GinContextGetPostFormMap") 24 | } 25 | } 26 | 27 | func (h *GinContextGetPostFormMap) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "GetPostFormMap") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextGetPostFormMap/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextGetPostFormMap 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func GetPostFormMap(c *gin.Context, key string) (map[string]string, bool) { 9 | reMap, flag := GetPostFormMapT(c, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(reMap), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "GetPostFormMap", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return reMap, flag 19 | } 20 | 21 | func GetPostFormMapT(c *gin.Context, key string) (map[string]string, bool) { 22 | return make(map[string]string), false 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextGetQueryArray/install.go: -------------------------------------------------------------------------------- 1 | package ginContextGetQueryArray 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextGetQueryArray"] = new(GinContextGetQueryArray) 12 | } 13 | 14 | type GinContextGetQueryArray struct { 15 | } 16 | 17 | func (h *GinContextGetQueryArray) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "GetQueryArray", GetQueryArray, GetQueryArrayT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextGetQueryArray") 22 | } else { 23 | fmt.Println("GinContextGetQueryArray") 24 | } 25 | } 26 | 27 | func (h *GinContextGetQueryArray) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "GetQueryArray") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextGetQueryArray/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextGetQueryArray 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func GetQueryArray(c *gin.Context, key string) ([]string, bool) { 9 | reArray, flag := GetQueryArrayT(c, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(reArray), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "GetQueryArray", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return reArray, flag 19 | } 20 | 21 | func GetQueryArrayT(c *gin.Context, key string) ([]string, bool) { 22 | return []string{}, false 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextGetQueryMap/install.go: -------------------------------------------------------------------------------- 1 | package ginContextGetQueryMap 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextGetQueryMap"] = new(GinContextGetQueryMap) 12 | } 13 | 14 | type GinContextGetQueryMap struct { 15 | } 16 | 17 | func (h *GinContextGetQueryMap) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "GetQueryMap", GetQueryMap, GetQueryMapT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextGetQueryMap") 22 | } else { 23 | fmt.Println("GinContextGetQueryMap") 24 | } 25 | } 26 | 27 | func (h *GinContextGetQueryMap) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "GetQueryMap") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextGetQueryMap/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextGetQueryMap 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func GetQueryMap(c *gin.Context, key string) (map[string]string, bool) { 9 | reMap, flag := GetQueryMapT(c, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(reMap), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "GetQueryMap", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return reMap, flag 19 | } 20 | 21 | func GetQueryMapT(c *gin.Context, key string) (map[string]string, bool) { 22 | return make(map[string]string), false 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextParam/install.go: -------------------------------------------------------------------------------- 1 | package ginContextParam 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextParam"] = new(GinContextParam) 12 | } 13 | 14 | type GinContextParam struct { 15 | } 16 | 17 | func (h *GinContextParam) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "Param", Param, ParamT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextParam") 22 | } else { 23 | fmt.Println("GinContextParam") 24 | } 25 | } 26 | 27 | func (h *GinContextParam) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "Param") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextParam/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextParam 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func Param(c *gin.Context, key string) string { 9 | str := ParamT(c, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(str), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "Param", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return str 19 | } 20 | 21 | func ParamT(c *gin.Context, key string) string { 22 | return "" 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindBodyWith/install.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindBodyWith 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextShouldBindBodyWith"] = new(GinContextShouldBindBodyWith) 12 | } 13 | 14 | type GinContextShouldBindBodyWith struct { 15 | } 16 | 17 | func (h *GinContextShouldBindBodyWith) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "ShouldBindBodyWith", ShouldBindBodyWith, ShouldBindBodyWithT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextShouldBindBodyWith") 22 | } else { 23 | fmt.Println("GinContextShouldBindBodyWith") 24 | } 25 | } 26 | 27 | func (h *GinContextShouldBindBodyWith) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "ShouldBindBodyWith") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindBodyWith/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindBodyWith 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | "github.com/gin-gonic/gin/binding" 7 | ) 8 | 9 | func ShouldBindBodyWith(c *gin.Context, obj interface{}, b binding.BindingBody) error { 10 | err := ShouldBindBodyWithT(c, obj, b) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(), 13 | Reqs: request.Collect(obj), 14 | Source: true, 15 | OriginClassName: "gin.(*Context)", 16 | MethodName: "ShouldBindBodyWith", 17 | ClassName: "gin.(*Context)", 18 | }) 19 | return err 20 | } 21 | 22 | func ShouldBindBodyWithT(c *gin.Context, obj interface{}, b binding.BindingBody) error { 23 | return nil 24 | } 25 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindUri/install.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindUri 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextShouldBindUri"] = new(GinContextShouldBindUri) 12 | } 13 | 14 | type GinContextShouldBindUri struct { 15 | } 16 | 17 | func (h *GinContextShouldBindUri) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "ShouldBindUri", ShouldBindUri, ShouldBindUriT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextShouldBindUri") 22 | } else { 23 | fmt.Println("GinContextShouldBindUri") 24 | } 25 | } 26 | 27 | func (h *GinContextShouldBindUri) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "ShouldBindUri") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindUri/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindUri 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | ) 7 | 8 | func ShouldBindUri(c *gin.Context, obj interface{}) error { 9 | err := ShouldBindUriT(c, obj) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(), 12 | Reqs: request.Collect(obj), 13 | Source: true, 14 | OriginClassName: "gin.(*Context)", 15 | MethodName: "ShouldBindUri", 16 | ClassName: "gin.(*Context)", 17 | }) 18 | return err 19 | } 20 | 21 | func ShouldBindUriT(c *gin.Context, obj interface{}) error { 22 | return nil 23 | } 24 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindWith/install.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindWith 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginContextShouldBindWith"] = new(GinContextShouldBindWith) 12 | } 13 | 14 | type GinContextShouldBindWith struct { 15 | } 16 | 17 | func (h *GinContextShouldBindWith) Hook() { 18 | context := &gin.Context{} 19 | err := gohook.HookMethod(context, "ShouldBindWith", ShouldBindWith, ShouldBindWithT) 20 | if err != nil { 21 | fmt.Println(err, "GinContextShouldBindWith") 22 | } else { 23 | fmt.Println("GinContextShouldBindWith") 24 | } 25 | } 26 | 27 | func (h *GinContextShouldBindWith) UnHook() { 28 | context := &gin.Context{} 29 | gohook.UnHookMethod(context, "ShouldBindWith") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginContextShouldBindWith/replacement.go: -------------------------------------------------------------------------------- 1 | package ginContextShouldBindWith 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/gin-gonic/gin" 6 | "github.com/gin-gonic/gin/binding" 7 | ) 8 | 9 | func ShouldBindWith(c *gin.Context, obj interface{}, b binding.Binding) error { 10 | err := ShouldBindWithT(c, obj, b) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(), 13 | Reqs: request.Collect(obj), 14 | Source: true, 15 | OriginClassName: "gin.(*Context)", 16 | MethodName: "ShouldBindWith", 17 | ClassName: "gin.(*Context)", 18 | }) 19 | return err 20 | } 21 | 22 | func ShouldBindWithT(c *gin.Context, obj interface{}, b binding.Binding) error { 23 | return nil 24 | } 25 | -------------------------------------------------------------------------------- /core/gin/ginEngineServerHTTP/install.go: -------------------------------------------------------------------------------- 1 | package ginEngineServerHTTP 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gin-gonic/gin" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["ginEngineServerHTTP"] = new(GinEngineServerHTTP) 12 | } 13 | 14 | type GinEngineServerHTTP struct { 15 | } 16 | 17 | func (h *GinEngineServerHTTP) Hook() { 18 | mux := &gin.Engine{} 19 | err := gohook.HookMethod(mux, "ServeHTTP", MyServer, MyServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "GinEngineServerHTTP") 22 | } else { 23 | fmt.Println("GinEngineServerHTTP") 24 | } 25 | } 26 | 27 | func (h *GinEngineServerHTTP) UnHook() { 28 | mux := &gin.Engine{} 29 | gohook.UnHookMethod(mux, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/gin/ginEngineServerHTTP/replacement.go: -------------------------------------------------------------------------------- 1 | package ginEngineServerHTTP 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "github.com/HXSecurity/DongTai-agent-go/api" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "github.com/gin-gonic/gin" 12 | "net/http" 13 | "reflect" 14 | "strconv" 15 | "strings" 16 | ) 17 | 18 | func MyServer(server *gin.Engine, w http.ResponseWriter, r *http.Request) { 19 | MyServerTemp(server, w, r) 20 | id := utils.CatGoroutineID() 21 | worker, _ := utils.NewWorker(global.AgentId) 22 | go func() { 23 | t := reflect.ValueOf(r.Body) 24 | var headerBase string 25 | body := "" 26 | for k, v := range r.Header { 27 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 28 | } 29 | 30 | TraceId := global.TraceId + "-" + strconv.Itoa(int(worker.GetId())) 31 | global.TargetTraceId = TraceId 32 | tranceID := TraceId + "." + strconv.Itoa(global.AgentId) + ".0.0.0" 33 | headerBase += "dt-traceid:" + tranceID 34 | if t.Kind() == reflect.Ptr { 35 | buf := t. 36 | Elem(). 37 | FieldByName("src"). 38 | Elem().Elem(). 39 | FieldByName("R"). 40 | Elem().Elem(). 41 | FieldByName("buf").Bytes() 42 | buf = buf[:bytes.IndexByte(buf, 0)] 43 | reader := bufio.NewReader(bytes.NewReader(buf)) 44 | var reqArr []string 45 | for { 46 | line, _, err := reader.ReadLine() 47 | if err != nil { 48 | break 49 | } 50 | reqArr = append(reqArr, string(line)) 51 | } 52 | body = reqArr[len(reqArr)-1] 53 | } 54 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 55 | scheme := "http" 56 | if r.TLS != nil { 57 | scheme = "https" 58 | } 59 | onlyKey := int(worker.GetId()) 60 | HookGroup := &request.UploadReq{ 61 | Type: 36, 62 | InvokeId: onlyKey, 63 | Detail: request.Detail{ 64 | AgentId: global.AgentId, 65 | Function: request.Function{ 66 | Method: r.Method, 67 | Url: scheme + "://" + r.Host + r.RequestURI, 68 | Uri: r.URL.Path, 69 | Protocol: r.Proto, 70 | ClientIp: r.RemoteAddr, 71 | Language: "GO", 72 | ReplayRequest: false, 73 | ReqHeader: header, 74 | ReqBody: body, 75 | QueryString: r.URL.RawQuery, 76 | Pool: []request.Pool{}, 77 | TraceId: tranceID, 78 | }, 79 | }, 80 | } 81 | var resBody string 82 | res, ok := global.ResponseMap.Load(id) 83 | if ok { 84 | global.ResponseMap.Delete(id) 85 | resBody = res.(string) 86 | } 87 | 88 | var resH string 89 | value2, ok1 := global.ResponseHeaderMap.Load(id) 90 | if ok1 { 91 | global.ResponseHeaderMap.Delete(id) 92 | resH = value2.(string) 93 | } 94 | for k, v := range w.Header() { 95 | resH += k + ": " + strings.Join(v, ",") + "\n" 96 | } 97 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 98 | HookGroup.Detail.ResHeader = resHeader 99 | HookGroup.Detail.ResBody = resBody 100 | goroutineIDs := make(map[string]bool) 101 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 102 | if value.(*request.PoolTree).IsThisBegin(id) { 103 | global.PoolTreeMap.Delete(key) 104 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 105 | return false 106 | } 107 | return true 108 | }) 109 | api.ReportUpload(*HookGroup) 110 | request.RunMapGCbYGoroutineID(goroutineIDs) 111 | }() 112 | return 113 | } 114 | 115 | func MyServerTemp(server *gin.Engine, w http.ResponseWriter, r *http.Request) { 116 | for i := 0; i < 100; i++ { 117 | 118 | } 119 | return 120 | } 121 | -------------------------------------------------------------------------------- /core/goChi/httpRouter/install.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/go-chi/chi/v5" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["chiRouter"] = new(ChiRouter) 12 | } 13 | 14 | type ChiRouter struct { 15 | } 16 | 17 | func (h *ChiRouter) Hook() { 18 | mux := &chi.Mux{} 19 | err := gohook.HookMethod(mux, "ServeHTTP", ChiRouterServer, ChiRouterServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "goChi") 22 | } else { 23 | fmt.Println("goChi") 24 | } 25 | } 26 | 27 | func (h *ChiRouter) UnHook() { 28 | mux := &chi.Mux{} 29 | gohook.UnHookMethod(mux, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/goChi/httpRouter/replacement.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "fmt" 8 | "github.com/HXSecurity/DongTai-agent-go/api" 9 | "github.com/HXSecurity/DongTai-agent-go/global" 10 | "github.com/HXSecurity/DongTai-agent-go/model/request" 11 | "github.com/HXSecurity/DongTai-agent-go/utils" 12 | "github.com/go-chi/chi/v5" 13 | "net/http" 14 | "reflect" 15 | "strings" 16 | ) 17 | 18 | func ChiRouterServer(server *chi.Mux, w http.ResponseWriter, r *http.Request) { 19 | request.FmtHookPool(request.PoolReq{ 20 | Args: request.Collect(r.Host), 21 | Reqs: request.Collect(r.Host), 22 | Source: true, 23 | OriginClassName: "chi.(*Mux)", 24 | MethodName: "ServeHTTP", 25 | ClassName: "chi", 26 | }) 27 | 28 | ChiRouterServerTemp(server, w, r) 29 | id := utils.CatGoroutineID() 30 | go func() { 31 | t := reflect.ValueOf(r.Body) 32 | var headerBase string 33 | body := "" 34 | for k, v := range r.Header { 35 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 36 | } 37 | if t.Kind() == reflect.Ptr { 38 | buf := t. 39 | Elem(). 40 | FieldByName("src"). 41 | Elem().Elem(). 42 | FieldByName("R"). 43 | Elem().Elem(). 44 | FieldByName("buf").Bytes() 45 | buf = buf[:bytes.IndexByte(buf, 0)] 46 | reader := bufio.NewReader(bytes.NewReader(buf)) 47 | var reqArr []string 48 | for { 49 | line, _, err := reader.ReadLine() 50 | if err != nil { 51 | break 52 | } 53 | reqArr = append(reqArr, string(line)) 54 | } 55 | body = reqArr[len(reqArr)-1] 56 | } 57 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 58 | scheme := "http" 59 | if r.TLS != nil { 60 | scheme = "https" 61 | } 62 | worker, err := utils.NewWorker(global.AgentId) 63 | if err != nil { 64 | fmt.Println(err) 65 | } 66 | onlyKey := int(worker.GetId()) 67 | HookGroup := &request.UploadReq{ 68 | Type: 36, 69 | InvokeId: onlyKey, 70 | Detail: request.Detail{ 71 | AgentId: global.AgentId, 72 | Function: request.Function{ 73 | Method: r.Method, 74 | Url: scheme + "://" + r.Host + r.RequestURI, 75 | Uri: r.URL.Path, 76 | Protocol: r.Proto, 77 | ClientIp: r.RemoteAddr, 78 | Language: "GO", 79 | ReplayRequest: false, 80 | ReqHeader: header, 81 | ReqBody: body, 82 | QueryString: r.URL.RawQuery, 83 | Pool: []request.Pool{}, 84 | //TraceId: tranceID, 85 | }, 86 | }, 87 | } 88 | var resBody string 89 | var resH string 90 | res, ok := global.ResponseMap.Load(id) 91 | if ok { 92 | global.ResponseMap.Delete(id) 93 | resBody = res.(string) 94 | } 95 | value2, ok2 := global.ResponseHeaderMap.Load(id) 96 | if ok2 { 97 | global.ResponseHeaderMap.Delete(id) 98 | resH = value2.(string) 99 | } 100 | for k, v := range w.Header() { 101 | resH += k + ": " + strings.Join(v, ",") + "\n" 102 | } 103 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 104 | HookGroup.Detail.ResHeader = resHeader 105 | HookGroup.Detail.ResBody = resBody 106 | goroutineIDs := make(map[string]bool) 107 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 108 | if value.(*request.PoolTree).IsThisBegin(id) { 109 | global.PoolTreeMap.Delete(key) 110 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 111 | return true 112 | } 113 | return true 114 | }) 115 | api.ReportUpload(*HookGroup) 116 | request.RunMapGCbYGoroutineID(goroutineIDs) 117 | }() 118 | return 119 | } 120 | 121 | func ChiRouterServerTemp(server *chi.Mux, w http.ResponseWriter, r *http.Request) { 122 | for i := 0; i < 100; i++ { 123 | 124 | } 125 | return 126 | } 127 | -------------------------------------------------------------------------------- /core/gorilla/gorillaRpcServerHTTP/install.go: -------------------------------------------------------------------------------- 1 | package gorillaRpcServerHTTP 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/gorilla/rpc/v2" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gorillaRpcServerHTTP"] = new(GorillaRpcServerHTTP) 12 | } 13 | 14 | type GorillaRpcServerHTTP struct { 15 | } 16 | 17 | func (h *GorillaRpcServerHTTP) Hook() { 18 | mux := &rpc.Server{} 19 | err := gohook.HookMethod(mux, "ServeHTTP", MyServer, MyServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "GorillaRpcServerHTTP") 22 | } else { 23 | fmt.Println("GorillaRpcServerHTTP") 24 | } 25 | } 26 | 27 | func (h *GorillaRpcServerHTTP) UnHook() { 28 | mux := &rpc.Server{} 29 | gohook.UnHookMethod(mux, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorilla/gorillaRpcServerHTTP/replacement.go: -------------------------------------------------------------------------------- 1 | package gorillaRpcServerHTTP 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "github.com/HXSecurity/DongTai-agent-go/api" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "github.com/gorilla/rpc/v2" 12 | "net/http" 13 | "reflect" 14 | "strings" 15 | ) 16 | 17 | func MyServer(server *rpc.Server, w http.ResponseWriter, r *http.Request) { 18 | MyServerTemp(server, w, r) 19 | id := utils.CatGoroutineID() 20 | go func() { 21 | t := reflect.ValueOf(r.Body) 22 | var headerBase string 23 | body := "" 24 | for k, v := range r.Header { 25 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 26 | } 27 | if t.Kind() == reflect.Ptr { 28 | 29 | buf := t. 30 | Elem(). 31 | FieldByName("ReadCloser"). 32 | Elem().Elem(). 33 | FieldByName("r"). 34 | Elem().Elem(). 35 | FieldByName("src"). 36 | Elem().Elem(). 37 | FieldByName("R"). 38 | Elem().Elem(). 39 | FieldByName("buf").Bytes() 40 | buf = buf[:bytes.IndexByte(buf, 0)] 41 | reader := bufio.NewReader(bytes.NewReader(buf)) 42 | var reqArr []string 43 | for { 44 | line, _, err := reader.ReadLine() 45 | if err != nil { 46 | break 47 | } 48 | reqArr = append(reqArr, string(line)) 49 | } 50 | body = reqArr[len(reqArr)-1] 51 | } 52 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 53 | scheme := "http" 54 | if r.TLS != nil { 55 | scheme = "https" 56 | } 57 | worker, _ := utils.NewWorker(global.AgentId) 58 | onlyKey := int(worker.GetId()) 59 | HookGroup := &request.UploadReq{ 60 | Type: 36, 61 | InvokeId: onlyKey, 62 | Detail: request.Detail{ 63 | AgentId: global.AgentId, 64 | Function: request.Function{ 65 | Method: r.Method, 66 | Url: scheme + "://" + r.Host + r.RequestURI, 67 | Uri: r.URL.Path, 68 | Protocol: r.Proto, 69 | ClientIp: r.RemoteAddr, 70 | Language: "GO", 71 | ReplayRequest: false, 72 | ReqHeader: header, 73 | ReqBody: body, 74 | QueryString: r.URL.RawQuery, 75 | Pool: []request.Pool{}, 76 | }, 77 | }, 78 | } 79 | var resBody string 80 | var resH string 81 | res, ok := global.ResponseMap.Load(id) 82 | if ok { 83 | global.ResponseMap.Delete(id) 84 | resBody = res.(string) 85 | } 86 | value2, ok2 := global.ResponseHeaderMap.Load(id) 87 | if ok2 { 88 | global.ResponseHeaderMap.Delete(id) 89 | resH = value2.(string) 90 | } 91 | for k, v := range w.Header() { 92 | resH += k + ": " + strings.Join(v, ",") + "\n" 93 | } 94 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 95 | HookGroup.Detail.ResHeader = resHeader 96 | HookGroup.Detail.ResBody = resBody 97 | goroutineIDs := make(map[string]bool) 98 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 99 | if value.(*request.PoolTree).IsThisBegin(id) { 100 | onlyKey += 1 101 | global.PoolTreeMap.Delete(key) 102 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 103 | return false 104 | } 105 | return true 106 | }) 107 | api.ReportUpload(*HookGroup) 108 | request.RunMapGCbYGoroutineID(goroutineIDs) 109 | }() 110 | return 111 | } 112 | 113 | func MyServerTemp(server *rpc.Server, w http.ResponseWriter, r *http.Request) { 114 | for i := 0; i < 100; i++ { 115 | 116 | } 117 | return 118 | } 119 | -------------------------------------------------------------------------------- /core/gorm/gormDBExec/install.go: -------------------------------------------------------------------------------- 1 | package gormDBExec 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBExec"] = new(GormDBExec) 12 | } 13 | 14 | type GormDBExec struct { 15 | } 16 | 17 | func (h *GormDBExec) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Exec", Exec, ExecT) 20 | if err != nil { 21 | fmt.Println(err, "gormExec") 22 | } else { 23 | fmt.Println("gormExec") 24 | } 25 | } 26 | 27 | func (h *GormDBExec) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Exec") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBExec/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBExec 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Exec(db *gorm.DB, sql string, values ...interface{}) (tx *gorm.DB) { 9 | s := ExecT(db, sql, values...) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(sql, values), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Exec", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func ExecT(db *gorm.DB, sql string, values ...interface{}) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/gorm/gormDBGroup/install.go: -------------------------------------------------------------------------------- 1 | package gormDBGroup 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBGroup"] = new(GormDBGroup) 12 | } 13 | 14 | type GormDBGroup struct { 15 | } 16 | 17 | func (h *GormDBGroup) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Group", Group, GroupT) 20 | if err != nil { 21 | fmt.Println(err, "gormGroup") 22 | } else { 23 | fmt.Println("gormGroup") 24 | } 25 | } 26 | 27 | func (h *GormDBGroup) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Group") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBGroup/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBGroup 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Group(db *gorm.DB, value string) (tx *gorm.DB) { 9 | s := GroupT(db, value) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(value), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Group", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func GroupT(db *gorm.DB, value string) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/gorm/gormDBHaving/install.go: -------------------------------------------------------------------------------- 1 | package gormDBHaving 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBHaving"] = new(GormDBHaving) 12 | } 13 | 14 | type GormDBHaving struct { 15 | } 16 | 17 | func (h *GormDBHaving) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Having", Having, HavingT) 20 | if err != nil { 21 | fmt.Println(err, "gormHaving") 22 | } else { 23 | fmt.Println("gormHavingr") 24 | } 25 | } 26 | 27 | func (h *GormDBHaving) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Having") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBHaving/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBHaving 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Having(db *gorm.DB, query interface{}, args ...interface{}) (tx *gorm.DB) { 9 | s := HavingT(db, query, args...) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(query, args), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Having", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func HavingT(db *gorm.DB, query interface{}, args ...interface{}) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/gorm/gormDBOrder/install.go: -------------------------------------------------------------------------------- 1 | package gormDBOrder 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBOrder"] = new(GormDBOrder) 12 | } 13 | 14 | type GormDBOrder struct { 15 | } 16 | 17 | func (h *GormDBOrder) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Order", Order, OrderT) 20 | if err != nil { 21 | fmt.Println(err, "gormOrder") 22 | } else { 23 | fmt.Println("gormOrder") 24 | } 25 | } 26 | 27 | func (h *GormDBOrder) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Order") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBOrder/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBOrder 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Order(db *gorm.DB, value interface{}) (tx *gorm.DB) { 9 | 10 | s := OrderT(db, value) 11 | request.FmtHookPool(request.PoolReq{ 12 | Args: request.Collect(value), 13 | Reqs: request.Collect(tx), 14 | Source: false, 15 | OriginClassName: "gorm.(*DB)", 16 | MethodName: "Order", 17 | ClassName: "gorm", 18 | }) 19 | return s 20 | } 21 | 22 | func OrderT(db *gorm.DB, value interface{}) (tx *gorm.DB) { 23 | return 24 | } 25 | -------------------------------------------------------------------------------- /core/gorm/gormDBPluck/install.go: -------------------------------------------------------------------------------- 1 | package gormDBPluck 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBPluck"] = new(GormDBPluck) 12 | } 13 | 14 | type GormDBPluck struct { 15 | } 16 | 17 | func (h *GormDBPluck) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Pluck", Pluck, PluckT) 20 | if err != nil { 21 | fmt.Println(err, "GormDBPluck") 22 | } else { 23 | fmt.Println("GormDBPluck") 24 | } 25 | } 26 | 27 | func (h *GormDBPluck) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Pluck") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBPluck/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBPluck 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Pluck(db *gorm.DB, column string, dest interface{}) (tx *gorm.DB) { 9 | s := PluckT(db, column, dest) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(column, dest), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Pluck", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func PluckT(db *gorm.DB, column string, dest interface{}) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/gorm/gormDBRaw/install.go: -------------------------------------------------------------------------------- 1 | package gormDBRaw 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBRaw"] = new(GormDBRaw) 12 | } 13 | 14 | type GormDBRaw struct { 15 | } 16 | 17 | func (h *GormDBRaw) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Raw", Raw, RawT) 20 | if err != nil { 21 | fmt.Println(err, "gormRaw") 22 | } else { 23 | fmt.Println("gormRaw") 24 | } 25 | } 26 | 27 | func (h *GormDBRaw) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Raw") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBRaw/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBRaw 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Raw(db *gorm.DB, sql string, values ...interface{}) (tx *gorm.DB) { 9 | s := RawT(db, sql, values...) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(sql, values), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Raw", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func RawT(db *gorm.DB, sql string, values ...interface{}) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/gorm/gormDBSelect/install.go: -------------------------------------------------------------------------------- 1 | package gormDBSelect 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "gorm.io/gorm" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["gormDBSelect"] = new(GormDBSelect) 12 | } 13 | 14 | type GormDBSelect struct { 15 | } 16 | 17 | func (h *GormDBSelect) Hook() { 18 | db := &gorm.DB{} 19 | err := gohook.HookMethod(db, "Select", Select, SelectT) 20 | if err != nil { 21 | fmt.Println(err, "gormOrder") 22 | } else { 23 | fmt.Println("gormOrder") 24 | } 25 | } 26 | 27 | func (h *GormDBSelect) UnHook() { 28 | db := &gorm.DB{} 29 | gohook.UnHookMethod(db, "Select") 30 | } 31 | -------------------------------------------------------------------------------- /core/gorm/gormDBSelect/replacement.go: -------------------------------------------------------------------------------- 1 | package gormDBSelect 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "gorm.io/gorm" 6 | ) 7 | 8 | func Select(db *gorm.DB, query interface{}, args ...interface{}) (tx *gorm.DB) { 9 | s := SelectT(db, query, args...) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(query, args), 12 | Reqs: request.Collect(tx), 13 | Source: false, 14 | OriginClassName: "gorm.(*DB)", 15 | MethodName: "Select", 16 | ClassName: "gorm", 17 | }) 18 | return s 19 | } 20 | 21 | func SelectT(db *gorm.DB, query interface{}, args ...interface{}) (tx *gorm.DB) { 22 | return 23 | } 24 | -------------------------------------------------------------------------------- /core/grpc/clientConn/install.go: -------------------------------------------------------------------------------- 1 | package clientConn 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "google.golang.org/grpc" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["grpcClientConn"] = new(GrpcClientConn) 12 | } 13 | 14 | type GrpcClientConn struct { 15 | } 16 | 17 | func (h *GrpcClientConn) Hook() { 18 | cl := &grpc.ClientConn{} 19 | err := gohook.HookMethod(cl, "Invoke", Invoke, InvokeT) 20 | if err != nil { 21 | fmt.Println(err, "GrpcClientConn") 22 | } else { 23 | fmt.Println("GrpcClientConn") 24 | } 25 | } 26 | 27 | func (h *GrpcClientConn) UnHook() { 28 | cl := &grpc.ClientConn{} 29 | gohook.UnHookMethod(cl, "Invoke") 30 | } 31 | -------------------------------------------------------------------------------- /core/grpc/clientConn/replacement.go: -------------------------------------------------------------------------------- 1 | package clientConn 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "strconv" 7 | "strings" 8 | 9 | "github.com/HXSecurity/DongTai-agent-go/global" 10 | "github.com/HXSecurity/DongTai-agent-go/model/request" 11 | "github.com/HXSecurity/DongTai-agent-go/utils" 12 | "google.golang.org/grpc" 13 | "google.golang.org/grpc/metadata" 14 | ) 15 | 16 | const ( 17 | TraceId = iota 18 | AgentId 19 | RoutineId 20 | NextKey 21 | OnlyKey 22 | ) 23 | 24 | func Invoke(cl *grpc.ClientConn, ctx context.Context, method string, args, reply interface{}, opts ...grpc.CallOption) error { 25 | outmd, _ := metadata.FromIncomingContext(ctx) 26 | worker, _ := utils.NewWorker(global.AgentId) 27 | var tranceid string 28 | if len(outmd.Get("dt-traceid")) > 0 { 29 | tranceid = outmd.Get("dt-traceid")[0] 30 | } 31 | if tranceid == "" { 32 | tranceid = global.TargetTraceId + "." + strconv.Itoa(global.AgentId) + ".0.1." + strconv.Itoa(int(worker.GetId())) 33 | } else { 34 | four := strconv.Itoa(int(worker.GetId())) 35 | tranceids := strings.Split(tranceid, ".") 36 | tranceids[AgentId] = strconv.Itoa(global.AgentId) 37 | num, _ := strconv.Atoi(tranceids[NextKey]) 38 | tranceids[NextKey] = strconv.Itoa(num + 1) 39 | tranceids[OnlyKey] = four 40 | newId := "" 41 | for i := 0; i < len(tranceids); i++ { 42 | if i == OnlyKey { 43 | newId += tranceids[i] 44 | } else { 45 | newId += tranceids[i] + "." 46 | } 47 | } 48 | tranceid = newId 49 | } 50 | md := metadata.Pairs("dt-traceid", tranceid, 51 | "protocol", "ProtoBuf", 52 | "requestURL", cl.Target()+method, 53 | "requestURI", method, 54 | "headers", "traceid:"+tranceid, 55 | ) 56 | fmt.Println(tranceid) 57 | ctx = metadata.NewOutgoingContext(ctx, md) 58 | err := InvokeT(cl, ctx, method, args, reply, opts...) 59 | request.FmtHookPool(request.PoolReq{ 60 | Args: request.Collect(args), 61 | Reqs: request.Collect(reply), 62 | Source: false, 63 | OriginClassName: "grpc.(*ClientConn)", 64 | MethodName: "Invoke", 65 | ClassName: "grpc.(*ClientConn)", 66 | TraceId: tranceid, 67 | Plugin: "GRPC", 68 | }) 69 | return err 70 | } 71 | func InvokeT(cl *grpc.ClientConn, ctx context.Context, method string, args, reply interface{}, opts ...grpc.CallOption) error { 72 | return nil 73 | } 74 | -------------------------------------------------------------------------------- /core/grpc/newServer/install.go: -------------------------------------------------------------------------------- 1 | package newServer 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "google.golang.org/grpc" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["grpcNewServer"] = new(GrpcNewServer) 12 | } 13 | 14 | type GrpcNewServer struct { 15 | } 16 | 17 | func (h *GrpcNewServer) Hook() { 18 | err := gohook.Hook(grpc.NewServer, NewServer, NewServerT) 19 | if err != nil { 20 | fmt.Println(err, "GrpcNewServer") 21 | } else { 22 | fmt.Println("GrpcNewServer") 23 | } 24 | } 25 | 26 | func (h *GrpcNewServer) UnHook() { 27 | gohook.UnHook(grpc.NewServer) 28 | } 29 | -------------------------------------------------------------------------------- /core/grpc/newServer/replacement.go: -------------------------------------------------------------------------------- 1 | package newServer 2 | 3 | import ( 4 | "context" 5 | "encoding/base64" 6 | "fmt" 7 | "github.com/HXSecurity/DongTai-agent-go/api" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "google.golang.org/grpc" 12 | "google.golang.org/grpc/metadata" 13 | "strconv" 14 | ) 15 | 16 | const ( 17 | TraceId = iota 18 | AgentId 19 | RoutineId 20 | NextKey 21 | OnlyKey 22 | ) 23 | 24 | func NewServer(opt ...grpc.ServerOption) *grpc.Server { 25 | opt = append(opt, grpc.UnaryInterceptor(interceptor)) 26 | return NewServerT(opt...) 27 | } 28 | 29 | // interceptor 一元拦截器 30 | func interceptor(ctx context.Context, req interface{}, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (interface{}, error) { 31 | md, _ := metadata.FromIncomingContext(ctx) 32 | worker, _ := utils.NewWorker(global.AgentId) 33 | dt := md.Get("dt-traceid") 34 | var Traceid = global.TargetTraceId + "." + strconv.Itoa(global.AgentId) + ".0.0." + strconv.Itoa(int(worker.GetId())) 35 | if len(dt) != 0 { 36 | Traceid = dt[0] 37 | } 38 | 39 | id := utils.CatGoroutineID() 40 | request.FmtHookPool(request.PoolReq{ 41 | Reqs: request.Collect(req), 42 | Args: request.Collect(req), 43 | Source: true, 44 | OriginClassName: "grpc", 45 | MethodName: "NewServer", 46 | ClassName: "grpc", 47 | TraceId: Traceid, 48 | }) 49 | // 获取metadata 50 | res, err := handler(ctx, req) 51 | go func() { 52 | worker, _ := utils.NewWorker(global.AgentId) 53 | onlyKey := int(worker.GetId()) 54 | header := base64.StdEncoding.EncodeToString([]byte("dt-traceid:" + Traceid)) 55 | HookGroup := &request.UploadReq{ 56 | Type: 36, 57 | InvokeId: onlyKey, 58 | Detail: request.Detail{ 59 | AgentId: global.AgentId, 60 | Function: request.Function{ 61 | Method: "RPC", 62 | Url: info.FullMethod, 63 | Uri: info.FullMethod, 64 | Protocol: "ProtoBuf", 65 | ClientIp: "", 66 | Language: "GO", 67 | Scheme: "GRPC", 68 | ReplayRequest: false, 69 | ReqHeader: header, 70 | ReqBody: "", 71 | QueryString: "", 72 | Pool: []request.Pool{}, 73 | TraceId: Traceid, 74 | }, 75 | }, 76 | } 77 | 78 | goroutineIDs := make(map[string]bool) 79 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 80 | if value.(*request.PoolTree).IsThisBegin(id) { 81 | global.PoolTreeMap.Delete(key) 82 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 83 | return false 84 | } 85 | return true 86 | }) 87 | 88 | fmt.Println(HookGroup.Detail.Function.Url) 89 | api.ReportUpload(*HookGroup) 90 | request.RunMapGCbYGoroutineID(goroutineIDs) 91 | }() 92 | return res, err 93 | } 94 | 95 | func NewServerT(opt ...grpc.ServerOption) *grpc.Server { 96 | return nil 97 | } 98 | -------------------------------------------------------------------------------- /core/http/httpHeaderGet/install.go: -------------------------------------------------------------------------------- 1 | package httpHeaderGet 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpHeaderGet"] = new(HttpHeaderGet) 12 | } 13 | 14 | type HttpHeaderGet struct { 15 | } 16 | 17 | func (h *HttpHeaderGet) Hook() { 18 | var header http.Header 19 | err := gohook.HookMethod(header, "Get", Get, GetT) 20 | if err != nil { 21 | fmt.Println(err, "HttpHeaderGet") 22 | } else { 23 | fmt.Println("HttpHeaderGet") 24 | } 25 | } 26 | 27 | func (h *HttpHeaderGet) UnHook() { 28 | var header *http.Header 29 | gohook.UnHookMethod(header, "Get") 30 | } 31 | -------------------------------------------------------------------------------- /core/http/httpHeaderGet/replacement.go: -------------------------------------------------------------------------------- 1 | package httpHeaderGet 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "github.com/HXSecurity/DongTai-agent-go/utils" 6 | "net/http" 7 | "strings" 8 | ) 9 | 10 | func Get(header http.Header, key string) string { 11 | values := GetT(header, key) 12 | skipMap := make(map[string]bool) 13 | skipMap["net/http.(*persistConn).roundTrip"] = true 14 | skipMap["net/http.(*chunkWriter).writeHeader"] = true 15 | skipMap["net/http.(*Client).makeHeadersCopier"] = true 16 | skipMap["net/http.(*persistConn).readLoop"] = true 17 | skipMap["net/http.(*Request).requiresHTTP1"] = true 18 | skipMap["net/http.isProtocolSwitchHeader"] = true 19 | if strings.Index(utils.LoadFunc(2), "github.com/parnurzeal/gorequest") > -1 { 20 | return values 21 | } 22 | if skipMap[utils.LoadFunc(2)] { 23 | return values 24 | } 25 | request.FmtHookPool(request.PoolReq{ 26 | Args: request.Collect(key), 27 | Reqs: request.Collect(values), 28 | Source: true, 29 | OriginClassName: "http.(Header)", 30 | MethodName: "Get", 31 | ClassName: "http.(Header)", 32 | }) 33 | return values 34 | } 35 | 36 | func GetT(header http.Header, key string) string { 37 | return "" 38 | } 39 | -------------------------------------------------------------------------------- /core/http/httpRequestCookie/install.go: -------------------------------------------------------------------------------- 1 | package httpRequestCookie 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpRequestCookie"] = new(HttpRequestCookie) 12 | } 13 | 14 | type HttpRequestCookie struct { 15 | } 16 | 17 | func (h *HttpRequestCookie) Hook() { 18 | var r *http.Request 19 | err := gohook.HookMethod(r, "Cookie", Cookie, CookieT) 20 | if err != nil { 21 | fmt.Println(err, "Cookie") 22 | } else { 23 | fmt.Println("Cookie") 24 | } 25 | } 26 | 27 | func (h *HttpRequestCookie) UnHook() { 28 | var r *http.Request 29 | gohook.UnHookMethod(r, "Cookie") 30 | } 31 | -------------------------------------------------------------------------------- /core/http/httpRequestCookie/replacement.go: -------------------------------------------------------------------------------- 1 | package httpRequestCookie 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "net/http" 6 | ) 7 | 8 | func Cookie(req *http.Request, name string) (*http.Cookie, error) { 9 | cookie, err := CookieT(req, name) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(name), 12 | Reqs: request.Collect(cookie, err), 13 | Source: true, 14 | OriginClassName: "http.(*Request)", 15 | MethodName: "Cookie", 16 | ClassName: "http.(*Request)", 17 | }) 18 | return cookie, err 19 | } 20 | 21 | func CookieT(req *http.Request, name string) (c *http.Cookie, e error) { 22 | return c, e 23 | } 24 | -------------------------------------------------------------------------------- /core/http/httpRequestFormValue/install.go: -------------------------------------------------------------------------------- 1 | package httpRequestFormValue 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpRequestFormValue"] = new(HttpRequestFormValue) 12 | } 13 | 14 | type HttpRequestFormValue struct { 15 | } 16 | 17 | func (h *HttpRequestFormValue) Hook() { 18 | var r *http.Request 19 | err := gohook.HookMethod(r, "FormValue", FormValue, FormValueT) 20 | if err != nil { 21 | fmt.Println(err, "FormValue") 22 | } else { 23 | fmt.Println("FormValue") 24 | } 25 | } 26 | 27 | func (h *HttpRequestFormValue) UnHook() { 28 | var r *http.Request 29 | gohook.UnHookMethod(r, "FormValue") 30 | } 31 | -------------------------------------------------------------------------------- /core/http/httpRequestFormValue/replacement.go: -------------------------------------------------------------------------------- 1 | package httpRequestFormValue 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "net/http" 6 | ) 7 | 8 | func FormValue(req *http.Request, key string) string { 9 | r := FormValueT(req, key) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(key), 12 | Reqs: request.Collect(r), 13 | Source: true, 14 | OriginClassName: "http.(*Request)", 15 | MethodName: "FormValue", 16 | ClassName: "http.(*Request)", 17 | }) 18 | return r 19 | } 20 | 21 | func FormValueT(r *http.Request, key string) string { 22 | return key 23 | } 24 | -------------------------------------------------------------------------------- /core/http/httpServeHTTP/install.go: -------------------------------------------------------------------------------- 1 | package httpServeHTTP 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpServeHTTP"] = new(HttpServeHTTP) 12 | } 13 | 14 | type HttpServeHTTP struct { 15 | } 16 | 17 | func (h *HttpServeHTTP) Hook() { 18 | mux := &http.ServeMux{} 19 | err := gohook.HookMethod(mux, "ServeHTTP", MyServer, MyServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "HttpServeHTTP") 22 | } else { 23 | fmt.Println("HttpServeHTTP") 24 | } 25 | } 26 | 27 | func (h *HttpServeHTTP) UnHook() { 28 | mux := &http.ServeMux{} 29 | gohook.UnHookMethod(mux, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/http/httpServeHTTP/replacement.go: -------------------------------------------------------------------------------- 1 | package httpServeHTTP 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "github.com/HXSecurity/DongTai-agent-go/api" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "net/http" 12 | "reflect" 13 | "strconv" 14 | "strings" 15 | ) 16 | 17 | func MyServer(server *http.ServeMux, w http.ResponseWriter, r *http.Request) { 18 | worker, _ := utils.NewWorker(global.AgentId) 19 | 20 | TraceId := global.TraceId + "-" + strconv.Itoa(int(worker.GetId())) 21 | global.TargetTraceId = TraceId 22 | MyServerTemp(server, w, r) 23 | id := utils.CatGoroutineID() 24 | go func() { 25 | t := reflect.ValueOf(r.Body) 26 | var headerBase string 27 | body := "" 28 | for k, v := range r.Header { 29 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 30 | } 31 | tranceID := TraceId + "." + strconv.Itoa(global.AgentId) + ".0.0.0" 32 | headerBase += "dt-traceid:" + tranceID 33 | if t.Kind() == reflect.Ptr { 34 | buf := t. 35 | Elem(). 36 | FieldByName("src"). 37 | Elem().Elem(). 38 | FieldByName("R"). 39 | Elem().Elem(). 40 | FieldByName("buf").Bytes() 41 | buf = buf[:bytes.IndexByte(buf, 0)] 42 | reader := bufio.NewReader(bytes.NewReader(buf)) 43 | var reqArr []string 44 | for { 45 | line, _, err := reader.ReadLine() 46 | if err != nil { 47 | break 48 | } 49 | reqArr = append(reqArr, string(line)) 50 | } 51 | body = reqArr[len(reqArr)-1] 52 | } 53 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 54 | scheme := "http" 55 | if r.TLS != nil { 56 | scheme = "https" 57 | } 58 | onlyKey := int(worker.GetId()) 59 | 60 | HookGroup := &request.UploadReq{ 61 | Type: 36, 62 | InvokeId: onlyKey, 63 | Detail: request.Detail{ 64 | AgentId: global.AgentId, 65 | Function: request.Function{ 66 | Method: r.Method, 67 | Url: scheme + "://" + r.Host + r.RequestURI, 68 | Uri: r.URL.Path, 69 | Protocol: r.Proto, 70 | ClientIp: r.RemoteAddr, 71 | Language: "GO", 72 | ReplayRequest: false, 73 | ReqHeader: header, 74 | ReqBody: body, 75 | QueryString: r.URL.RawQuery, 76 | Pool: []request.Pool{}, 77 | TraceId: tranceID, 78 | }, 79 | }, 80 | } 81 | var resBody string 82 | var resH string 83 | res, ok := global.ResponseMap.Load(id) 84 | if ok { 85 | global.ResponseMap.Delete(id) 86 | resBody = res.(string) 87 | } 88 | value2, ok2 := global.ResponseHeaderMap.Load(id) 89 | if ok2 { 90 | global.ResponseHeaderMap.Delete(id) 91 | resH = value2.(string) 92 | } 93 | for k, v := range w.Header() { 94 | resH += k + ": " + strings.Join(v, ",") + "\n" 95 | } 96 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 97 | HookGroup.Detail.ResHeader = resHeader 98 | HookGroup.Detail.ResBody = resBody 99 | goroutineIDs := make(map[string]bool) 100 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 101 | if value.(*request.PoolTree).IsThisBegin(id) { 102 | global.PoolTreeMap.Delete(key) 103 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 104 | return false 105 | } 106 | return true 107 | }) 108 | api.ReportUpload(*HookGroup) 109 | request.RunMapGCbYGoroutineID(goroutineIDs) 110 | }() 111 | return 112 | } 113 | 114 | func MyServerTemp(server *http.ServeMux, w http.ResponseWriter, r *http.Request) { 115 | for i := 0; i < 100; i++ { 116 | 117 | } 118 | return 119 | } 120 | -------------------------------------------------------------------------------- /core/http/urlURLQuery/install.go: -------------------------------------------------------------------------------- 1 | package urlURLQuery 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "net/http" 8 | "net/url" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["urlURLQuery"] = new(UrlURLQuery) 13 | } 14 | 15 | type UrlURLQuery struct { 16 | } 17 | 18 | func (h *UrlURLQuery) Hook() { 19 | var URL *url.URL 20 | err := gohook.HookMethod(URL, "Query", Query, QueryT) 21 | if err != nil { 22 | fmt.Println(err, "UrlURLQuery") 23 | } else { 24 | fmt.Println("UrlURLQuery") 25 | } 26 | } 27 | 28 | func (h *UrlURLQuery) UnHook() { 29 | var r *http.Request 30 | gohook.UnHookMethod(r, "UrlURLQuery") 31 | } 32 | -------------------------------------------------------------------------------- /core/http/urlURLQuery/replacement.go: -------------------------------------------------------------------------------- 1 | package urlURLQuery 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model/request" 5 | "net/url" 6 | ) 7 | 8 | func Query(URL *url.URL) url.Values { 9 | values := QueryT(URL) 10 | request.FmtHookPool(request.PoolReq{ 11 | Args: request.Collect(), 12 | Reqs: request.Collect(values), 13 | Source: true, 14 | OriginClassName: "url.(*URL)", 15 | MethodName: "Query", 16 | ClassName: "url.(*URL)", 17 | }) 18 | return values 19 | } 20 | 21 | func QueryT(URL *url.URL) url.Values { 22 | return url.Values{} 23 | } 24 | -------------------------------------------------------------------------------- /core/httpRouter/httpRouter/install.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/julienschmidt/httprouter" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["httpRouter"] = new(HttpRouter) 12 | } 13 | 14 | type HttpRouter struct { 15 | } 16 | 17 | func (h *HttpRouter) Hook() { 18 | mux := &httprouter.Router{} 19 | err := gohook.HookMethod(mux, "ServeHTTP", MyHttpRouterServer, MyHttpRouterServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "HttpRouter") 22 | } else { 23 | fmt.Println("HttpRouter") 24 | } 25 | } 26 | 27 | func (h *HttpRouter) UnHook() { 28 | mux := &httprouter.Router{} 29 | gohook.UnHookMethod(mux, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/httpRouter/httpRouter/replacement.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "fmt" 8 | "github.com/HXSecurity/DongTai-agent-go/api" 9 | "github.com/HXSecurity/DongTai-agent-go/global" 10 | "github.com/HXSecurity/DongTai-agent-go/model/request" 11 | "github.com/HXSecurity/DongTai-agent-go/utils" 12 | "github.com/julienschmidt/httprouter" 13 | "net/http" 14 | "reflect" 15 | "strconv" 16 | "strings" 17 | ) 18 | 19 | func MyHttpRouterServer(server *httprouter.Router, w http.ResponseWriter, r *http.Request) { 20 | worker, err := utils.NewWorker(global.AgentId) 21 | request.FmtHookPool(request.PoolReq{ 22 | Args: request.Collect(r.Host), 23 | Reqs: request.Collect(r.Host), 24 | Source: true, 25 | OriginClassName: "httprouter.(*Router)", 26 | MethodName: "ServeHTTP", 27 | ClassName: "httprouter", 28 | }) 29 | 30 | MyHttpRouterServerTemp(server, w, r) 31 | id := utils.CatGoroutineID() 32 | go func() { 33 | t := reflect.ValueOf(r.Body) 34 | var headerBase string 35 | body := "" 36 | for k, v := range r.Header { 37 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 38 | } 39 | TraceId := global.TraceId + "-" + strconv.Itoa(int(worker.GetId())) 40 | global.TargetTraceId = TraceId 41 | tranceID := TraceId + "." + strconv.Itoa(global.AgentId) + ".0.0.0" 42 | headerBase += "dt-traceid:" + tranceID 43 | if t.Kind() == reflect.Ptr { 44 | buf := t. 45 | Elem(). 46 | FieldByName("src"). 47 | Elem().Elem(). 48 | FieldByName("R"). 49 | Elem().Elem(). 50 | FieldByName("buf").Bytes() 51 | buf = buf[:bytes.IndexByte(buf, 0)] 52 | reader := bufio.NewReader(bytes.NewReader(buf)) 53 | var reqArr []string 54 | for { 55 | line, _, err := reader.ReadLine() 56 | if err != nil { 57 | break 58 | } 59 | reqArr = append(reqArr, string(line)) 60 | } 61 | body = reqArr[len(reqArr)-1] 62 | } 63 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 64 | scheme := "http" 65 | if r.TLS != nil { 66 | scheme = "https" 67 | } 68 | if err != nil { 69 | fmt.Println(err) 70 | } 71 | onlyKey := int(worker.GetId()) 72 | HookGroup := &request.UploadReq{ 73 | Type: 36, 74 | InvokeId: onlyKey, 75 | Detail: request.Detail{ 76 | AgentId: global.AgentId, 77 | Function: request.Function{ 78 | Method: r.Method, 79 | Url: scheme + "://" + r.Host + r.RequestURI, 80 | Uri: r.URL.Path, 81 | Protocol: r.Proto, 82 | ClientIp: r.RemoteAddr, 83 | Language: "GO", 84 | ReplayRequest: false, 85 | ReqHeader: header, 86 | ReqBody: body, 87 | QueryString: r.URL.RawQuery, 88 | Pool: []request.Pool{}, 89 | TraceId: tranceID, 90 | }, 91 | }, 92 | } 93 | var resBody string 94 | var resH string 95 | res, ok := global.ResponseMap.Load(id) 96 | if ok { 97 | global.ResponseMap.Delete(id) 98 | resBody = res.(string) 99 | } 100 | value2, ok2 := global.ResponseHeaderMap.Load(id) 101 | if ok2 { 102 | global.ResponseHeaderMap.Delete(id) 103 | resH = value2.(string) 104 | } 105 | for k, v := range w.Header() { 106 | resH += k + ": " + strings.Join(v, ",") + "\n" 107 | } 108 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 109 | HookGroup.Detail.ResHeader = resHeader 110 | HookGroup.Detail.ResBody = resBody 111 | goroutineIDs := make(map[string]bool) 112 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 113 | if value.(*request.PoolTree).IsThisBegin(id) { 114 | global.PoolTreeMap.Delete(key) 115 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 116 | return true 117 | } 118 | return true 119 | }) 120 | api.ReportUpload(*HookGroup) 121 | request.RunMapGCbYGoroutineID(goroutineIDs) 122 | }() 123 | return 124 | } 125 | 126 | func MyHttpRouterServerTemp(server *httprouter.Router, w http.ResponseWriter, r *http.Request) { 127 | for i := 0; i < 100; i++ { 128 | 129 | } 130 | return 131 | } 132 | -------------------------------------------------------------------------------- /core/kafkaGo/kafkaWriter/install.go: -------------------------------------------------------------------------------- 1 | package kafkaWriter 2 | 3 | import ( 4 | "fmt" 5 | 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "github.com/brahma-adshonor/gohook" 8 | "github.com/segmentio/kafka-go" 9 | ) 10 | 11 | func init() { 12 | model.HookMap["kafkaGoWriter"] = new(KafkaWriter) 13 | } 14 | 15 | type KafkaWriter struct { 16 | } 17 | 18 | func (h *KafkaWriter) Hook() { 19 | w := &kafka.Writer{} 20 | err := gohook.HookMethod(w, "WriteMessages", WriteMessages, WriteMessagesT) 21 | if err != nil { 22 | fmt.Println(err, "kafkaGoWriter") 23 | } else { 24 | fmt.Println("kafkaGoWriter") 25 | } 26 | } 27 | 28 | func (h *KafkaWriter) UnHook() { 29 | cl := &kafka.Writer{} 30 | gohook.UnHookMethod(cl, "WriteMessages") 31 | } 32 | -------------------------------------------------------------------------------- /core/kafkaGo/kafkaWriter/replacement.go: -------------------------------------------------------------------------------- 1 | package kafkaWriter 2 | 3 | import ( 4 | "context" 5 | "fmt" 6 | "reflect" 7 | "strconv" 8 | "strings" 9 | 10 | "github.com/HXSecurity/DongTai-agent-go/global" 11 | "github.com/HXSecurity/DongTai-agent-go/model/request" 12 | "github.com/HXSecurity/DongTai-agent-go/utils" 13 | "github.com/segmentio/kafka-go" 14 | "google.golang.org/grpc/metadata" 15 | ) 16 | 17 | const ( 18 | TraceId = iota 19 | AgentId 20 | RoutineId 21 | NextKey 22 | OnlyKey 23 | ) 24 | 25 | func WriteMessages(w *kafka.Writer, ctx context.Context, msgs ...kafka.Message) error { 26 | for idx, msg := range msgs { 27 | traceId := getTraceId(ctx) 28 | msgs[idx].Headers = append(msg.Headers, kafka.Header{ 29 | Key: "dt-traceid", 30 | Value: []byte(traceId), 31 | }) 32 | 33 | fmt.Println("traceId:", traceId, "msg:", msg.Value) 34 | v := reflect.ValueOf(msg.Value) 35 | request.FmtHookPool(request.PoolReq{ 36 | Args: request.Collect(msg.Value), 37 | NeedHook: request.Collect(v.Pointer()), 38 | Source: false, 39 | OriginClassName: "kafka.(*Writer)", 40 | MethodName: "WriteMessages", 41 | ClassName: "kafka.(*Writer)", 42 | TraceId: traceId, 43 | Plugin: "KAFKA", 44 | }) 45 | } 46 | 47 | err := WriteMessagesT(w, ctx, msgs...) 48 | return err 49 | } 50 | 51 | func getTraceId(ctx context.Context) string { 52 | outmd, _ := metadata.FromIncomingContext(ctx) 53 | worker, _ := utils.NewWorker(global.AgentId) 54 | var tranceid string 55 | if len(outmd.Get("dt-traceid")) > 0 { 56 | tranceid = outmd.Get("dt-traceid")[0] 57 | } 58 | if tranceid == "" { 59 | tranceid = global.TargetTraceId + "." + strconv.Itoa(global.AgentId) + ".0.1." + strconv.Itoa(int(worker.GetId())) 60 | } else { 61 | four := strconv.Itoa(int(worker.GetId())) 62 | tranceids := strings.Split(tranceid, ".") 63 | tranceids[AgentId] = strconv.Itoa(global.AgentId) 64 | num, _ := strconv.Atoi(tranceids[NextKey]) 65 | tranceids[NextKey] = strconv.Itoa(num + 1) 66 | tranceids[OnlyKey] = four 67 | newId := "" 68 | for i := 0; i < len(tranceids); i++ { 69 | if i == OnlyKey { 70 | newId += tranceids[i] 71 | } else { 72 | newId += tranceids[i] + "." 73 | } 74 | } 75 | tranceid = newId 76 | } 77 | 78 | return tranceid 79 | } 80 | 81 | func WriteMessagesT(w *kafka.Writer, ctx context.Context, msgs ...kafka.Message) error { 82 | return nil 83 | } 84 | -------------------------------------------------------------------------------- /core/mux/muxServerHTTP/install.go: -------------------------------------------------------------------------------- 1 | package muxServeHTTP 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | "github.com/brahma-adshonor/gohook" 7 | "github.com/go-mux/mux" 8 | ) 9 | 10 | func init() { 11 | model.HookMap["muxServeHTTP"] = new(MuxServeHTTP) 12 | } 13 | 14 | type MuxServeHTTP struct { 15 | } 16 | 17 | func (h *MuxServeHTTP) Hook() { 18 | mx := &mux.Router{} 19 | err := gohook.HookMethod(mx, "ServeHTTP", MyServer, MyServerTemp) 20 | if err != nil { 21 | fmt.Println(err, "HttpServeHTTP") 22 | } else { 23 | fmt.Println("HttpServeHTTP") 24 | } 25 | } 26 | 27 | func (h *MuxServeHTTP) UnHook() { 28 | mx := &mux.Router{} 29 | gohook.UnHookMethod(mx, "ServeHTTP") 30 | } 31 | -------------------------------------------------------------------------------- /core/mux/muxServerHTTP/replacement.go: -------------------------------------------------------------------------------- 1 | package muxServeHTTP 2 | 3 | import ( 4 | "bufio" 5 | "bytes" 6 | "encoding/base64" 7 | "github.com/HXSecurity/DongTai-agent-go/api" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "github.com/go-mux/mux" 12 | "net/http" 13 | "reflect" 14 | "strconv" 15 | "strings" 16 | ) 17 | 18 | func MyServer(server *mux.Router, w http.ResponseWriter, r *http.Request) { 19 | worker, _ := utils.NewWorker(global.AgentId) 20 | 21 | TraceId := global.TraceId + "-" + strconv.Itoa(int(worker.GetId())) 22 | global.TargetTraceId = TraceId 23 | MyServerTemp(server, w, r) 24 | id := utils.CatGoroutineID() 25 | go func() { 26 | t := reflect.ValueOf(r.Body) 27 | var headerBase string 28 | body := "" 29 | for k, v := range r.Header { 30 | headerBase += k + ": " + strings.Join(v, ",") + "\n" 31 | } 32 | tranceID := TraceId + "." + strconv.Itoa(global.AgentId) + ".0.0.0" 33 | headerBase += "dt-traceid:" + tranceID 34 | if t.Kind() == reflect.Ptr { 35 | buf := t. 36 | Elem(). 37 | FieldByName("src"). 38 | Elem().Elem(). 39 | FieldByName("R"). 40 | Elem().Elem(). 41 | FieldByName("buf").Bytes() 42 | buf = buf[:bytes.IndexByte(buf, 0)] 43 | reader := bufio.NewReader(bytes.NewReader(buf)) 44 | var reqArr []string 45 | for { 46 | line, _, err := reader.ReadLine() 47 | if err != nil { 48 | break 49 | } 50 | reqArr = append(reqArr, string(line)) 51 | } 52 | body = reqArr[len(reqArr)-1] 53 | } 54 | header := base64.StdEncoding.EncodeToString([]byte(headerBase)) 55 | scheme := "http" 56 | if r.TLS != nil { 57 | scheme = "https" 58 | } 59 | onlyKey := int(worker.GetId()) 60 | 61 | HookGroup := &request.UploadReq{ 62 | Type: 36, 63 | InvokeId: onlyKey, 64 | Detail: request.Detail{ 65 | AgentId: global.AgentId, 66 | Function: request.Function{ 67 | Method: r.Method, 68 | Url: scheme + "://" + r.Host + r.RequestURI, 69 | Uri: r.URL.Path, 70 | Protocol: r.Proto, 71 | ClientIp: r.RemoteAddr, 72 | Language: "GO", 73 | ReplayRequest: false, 74 | ReqHeader: header, 75 | ReqBody: body, 76 | QueryString: r.URL.RawQuery, 77 | Pool: []request.Pool{}, 78 | TraceId: tranceID, 79 | }, 80 | }, 81 | } 82 | var resBody string 83 | var resH string 84 | res, ok := global.ResponseMap.Load(id) 85 | if ok { 86 | global.ResponseMap.Delete(id) 87 | resBody = res.(string) 88 | } 89 | value2, ok2 := global.ResponseHeaderMap.Load(id) 90 | if ok2 { 91 | global.ResponseHeaderMap.Delete(id) 92 | resH = value2.(string) 93 | } 94 | for k, v := range w.Header() { 95 | resH += k + ": " + strings.Join(v, ",") + "\n" 96 | } 97 | resHeader := base64.StdEncoding.EncodeToString([]byte(resH)) 98 | HookGroup.Detail.ResHeader = resHeader 99 | HookGroup.Detail.ResBody = resBody 100 | goroutineIDs := make(map[string]bool) 101 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 102 | if value.(*request.PoolTree).IsThisBegin(id) { 103 | global.PoolTreeMap.Delete(key) 104 | value.(*request.PoolTree).FMT(&HookGroup.Detail.Function.Pool, worker, goroutineIDs, HookGroup.Detail.Function.TraceId) 105 | return false 106 | } 107 | return true 108 | }) 109 | api.ReportUpload(*HookGroup) 110 | request.RunMapGCbYGoroutineID(goroutineIDs) 111 | }() 112 | return 113 | } 114 | 115 | func MyServerTemp(server *mux.Router, w http.ResponseWriter, r *http.Request) { 116 | for i := 0; i < 100; i++ { 117 | 118 | } 119 | return 120 | } 121 | -------------------------------------------------------------------------------- /global/config.go: -------------------------------------------------------------------------------- 1 | package global 2 | 3 | import ( 4 | "flag" 5 | "fmt" 6 | "github.com/HXSecurity/DongTai-agent-go/model" 7 | "gopkg.in/yaml.v3" 8 | "io/ioutil" 9 | ) 10 | 11 | var Config model.Config 12 | 13 | func InitViper() { 14 | config, err := ioutil.ReadFile("dongtai-go-agent-config.yaml") 15 | fmt.Println(string(config)) 16 | if err != nil { 17 | fmt.Println(err) 18 | return 19 | } 20 | err = yaml.Unmarshal(config, &Config) 21 | if err != nil { 22 | fmt.Println(err) 23 | return 24 | } 25 | 26 | var version string 27 | var name string 28 | var auto bool 29 | var projectGroupId int 30 | var projectTemplateId int 31 | 32 | flag.StringVar(&version, "DongtaiGoProjectVersion", "v1.0.0", "Project Version") 33 | flag.StringVar(&name, "DongtaiGoProjectName", "GO Project", "Project Name") 34 | flag.BoolVar(&auto, "DongtaiGoProjectCreate", true, "Auto Create Project") 35 | flag.IntVar(&projectGroupId, "DongtaiGoProjectGroupId", 1, "Group ID") 36 | flag.IntVar(&projectTemplateId, "DongtaiGoProjectTemplateId", 1, "Template ID") 37 | 38 | flag.Parse() 39 | if version != "v1.0.0" { 40 | Config.DongtaiGoProjectVersion = version 41 | } 42 | if name != "GO Project" { 43 | Config.DongtaiGoProjectName = name 44 | } 45 | if auto != true { 46 | Config.DongtaiGoProjectCreate = auto 47 | } 48 | if projectGroupId != 1 { 49 | Config.DongtaiGoProjectGroupId = projectGroupId 50 | } 51 | if projectTemplateId != 1 { 52 | Config.DongtaiGoProjectTemplateId = projectTemplateId 53 | } 54 | 55 | fmt.Println(Config) 56 | } 57 | -------------------------------------------------------------------------------- /global/status.go: -------------------------------------------------------------------------------- 1 | package global 2 | 3 | import ( 4 | "github.com/HXSecurity/DongTai-agent-go/model" 5 | "sync" 6 | ) 7 | 8 | type HashKeys []string 9 | 10 | func (h *HashKeys) Some(source []string) bool { 11 | for i := 0; i < len(*h); i++ { 12 | for k := 0; k < len(source); k++ { 13 | if (*h)[i] == source[k] { 14 | return true 15 | } 16 | } 17 | } 18 | return false 19 | } 20 | 21 | var ( 22 | AllHooks []model.HookStruct 23 | AgentId = 0 24 | PoolTreeMap = sync.Map{} 25 | ResponseMap = sync.Map{} 26 | ResponseHeaderMap = sync.Map{} 27 | TraceId string 28 | TargetTraceId string 29 | ) 30 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/HXSecurity/DongTai-agent-go 2 | 3 | go 1.11 4 | 5 | require ( 6 | github.com/brahma-adshonor/gohook v1.1.9 7 | github.com/gin-gonic/gin v1.7.7 8 | github.com/julienschmidt/httprouter v1.3.0 9 | github.com/parnurzeal/gorequest v0.2.16 10 | github.com/pkg/errors v0.9.1 11 | github.com/shirou/gopsutil v3.21.10+incompatible 12 | gorm.io/gorm v1.20.11 13 | ) 14 | 15 | require ( 16 | github.com/StackExchange/wmi v1.2.1 // indirect 17 | github.com/elazarl/goproxy v0.0.0-20210801061803-8e322dfb79c4 // indirect 18 | github.com/go-chi/chi/v5 v5.0.7 19 | github.com/go-mux/mux v1.0.0 20 | github.com/gorilla/rpc v1.2.0 21 | github.com/jinzhu/now v1.1.3 // indirect 22 | github.com/json-iterator/go v1.1.11 // indirect 23 | github.com/modern-go/reflect2 v1.0.1 // indirect 24 | github.com/segmentio/kafka-go v0.4.31 25 | github.com/smartystreets/goconvey v1.7.2 // indirect 26 | github.com/tklauser/go-sysconf v0.3.9 // indirect 27 | golang.org/x/crypto v0.0.0-20210817164053-32db794688a5 // indirect 28 | golang.org/x/net v0.0.0-20211109214657-ef0fda0de508 // indirect 29 | golang.org/x/sys v0.0.0-20210823070655-63515b42dcdf // indirect 30 | google.golang.org/grpc v1.45.0 31 | google.golang.org/protobuf v1.27.1 // indirect 32 | gopkg.in/yaml.v2 v2.4.0 // indirect 33 | gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b 34 | moul.io/http2curl v1.0.0 // indirect 35 | ) 36 | -------------------------------------------------------------------------------- /hook/base.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Base struct { 4 | } 5 | 6 | func (b *Base) GetHook() []string { 7 | return []string{ 8 | "sqlDBQuery", 9 | "fmtSprintf", 10 | "jsonUnmarshal", 11 | "jsonDecoderDecode", 12 | "jsonNewDecoder", 13 | "runtimeConcatstrings", 14 | "execCommand", 15 | "execCmdStart", 16 | "bufioWriterWrite", 17 | "bufioWriterWriteString", 18 | "runtimesSringtoslicebyte", 19 | "htmlTemplateExecuteTemplate", 20 | "httpClientDo", 21 | "httpNewRequest", 22 | "stringsBuilderWriteString", 23 | "osOpenFile", 24 | "ioReadAll", 25 | "regexpRegexpReplaceAllString", 26 | "urlUrlString", 27 | } 28 | } 29 | 30 | func (b *Base) HookAll() { 31 | Hook(b.GetHook()) 32 | } 33 | 34 | func (b *Base) UnHookAll() { 35 | UnHook(b.GetHook()) 36 | } 37 | -------------------------------------------------------------------------------- /hook/gin.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Gin struct { 4 | } 5 | 6 | func (g *Gin) GetHook() []string { 7 | return []string{ 8 | "ginEngineServerHTTP", 9 | "ginContextShouldBindWith", 10 | "ginContextShouldBindUri", 11 | "ginContextShouldBindBodyWith", 12 | "ginContextParam", 13 | "ginContextGetQueryMap", 14 | "ginContextGetQueryArray", 15 | "ginContextGetPostFormMap", 16 | "ginContextGetPostFormArray", 17 | "httpRequestCookie", 18 | } 19 | } 20 | 21 | func (g *Gin) HookAll() { 22 | Hook(g.GetHook()) 23 | } 24 | 25 | func (g *Gin) UnHookAll() { 26 | UnHook(g.GetHook()) 27 | } 28 | -------------------------------------------------------------------------------- /hook/goChi.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type ChiRouter struct { 4 | } 5 | 6 | func (h *ChiRouter) GetHook() []string { 7 | return []string{ 8 | "chiRouter", 9 | "httpRequestFormValue", 10 | "httpRequestCookie", 11 | "urlURLQuery", 12 | } 13 | } 14 | 15 | func (h *ChiRouter) HookAll() { 16 | Hook(h.GetHook()) 17 | } 18 | 19 | func (h *ChiRouter) UnHookAll() { 20 | UnHook(h.GetHook()) 21 | } 22 | -------------------------------------------------------------------------------- /hook/gorilla.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Gorilla struct { 4 | } 5 | 6 | func (g *Gorilla) GetHook() []string { 7 | return []string{ 8 | "gorillaRpcServerHTTP", 9 | } 10 | } 11 | 12 | func (g *Gorilla) HookAll() { 13 | Hook(g.GetHook()) 14 | } 15 | 16 | func (g *Gorilla) UnHookAll() { 17 | UnHook(g.GetHook()) 18 | } 19 | -------------------------------------------------------------------------------- /hook/gorm.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Gorm struct { 4 | } 5 | 6 | func (g *Gorm) GetHook() []string { 7 | return []string{ 8 | "gormDBOrder", 9 | "gormDBExec", 10 | "gormDBGroup", 11 | "gormDBHaving", 12 | "gormDBPluck", 13 | "gormDBRaw", 14 | "gormDBSelect", 15 | } 16 | } 17 | 18 | func (g *Gorm) HookAll() { 19 | Hook(g.GetHook()) 20 | } 21 | 22 | func (g *Gorm) UnHookAll() { 23 | UnHook(g.GetHook()) 24 | } 25 | -------------------------------------------------------------------------------- /hook/grpc.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Grpc struct { 4 | } 5 | 6 | func (g *Grpc) GetHook() []string { 7 | return []string{ 8 | "grpcClientConn", 9 | "grpcNewServer", 10 | } 11 | } 12 | 13 | func (g *Grpc) HookAll() { 14 | Hook(g.GetHook()) 15 | } 16 | 17 | func (g *Grpc) UnHookAll() { 18 | UnHook(g.GetHook()) 19 | } 20 | -------------------------------------------------------------------------------- /hook/hook.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | import ( 4 | "fmt" 5 | "github.com/HXSecurity/DongTai-agent-go/model" 6 | ) 7 | 8 | //此处为定义了Hook的注册方法和卸载方法 9 | 10 | func HookFunc(s string) { 11 | if model.HookMap[s] == nil { 12 | fmt.Println("尚未注册此HOOK:", s) 13 | } else { 14 | model.HookMap[s].Hook() 15 | } 16 | } 17 | 18 | func UnHookFunc(s string) { 19 | if model.HookMap[s] == nil { 20 | fmt.Println("尚未注册此HOOK") 21 | } else { 22 | model.HookMap[s].UnHook() 23 | } 24 | } 25 | 26 | func Hook(funcs []string) { 27 | for i := range funcs { 28 | HookFunc(funcs[i]) 29 | } 30 | } 31 | 32 | func UnHook(funcs []string) { 33 | for i := range funcs { 34 | UnHookFunc(funcs[i]) 35 | } 36 | } 37 | 38 | func HookAll(h ...model.HookStruct) { 39 | for i := range h { 40 | h[i].HookAll() 41 | } 42 | } 43 | 44 | func UnHookAll(h ...model.HookStruct) { 45 | for i := range h { 46 | h[i].UnHookAll() 47 | } 48 | } 49 | 50 | func RunAllHook() { 51 | HookAll( 52 | new(Base), 53 | new(Gin), 54 | new(Gorilla), 55 | new(Gorm), 56 | new(Http), 57 | new(HttpRouter), 58 | ) 59 | } 60 | 61 | func StopAllHook() { 62 | UnHookAll( 63 | new(Base), 64 | new(Gin), 65 | new(Gorilla), 66 | new(Gorm), 67 | new(Http), 68 | new(HttpRouter), 69 | ) 70 | } 71 | -------------------------------------------------------------------------------- /hook/http.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Http struct { 4 | } 5 | 6 | func (h *Http) GetHook() []string { 7 | return []string{ 8 | "httpHeaderGet", 9 | "httpRequestCookie", 10 | "httpServeHTTP", 11 | "httpRequestFormValue", 12 | "urlURLQuery", 13 | } 14 | } 15 | 16 | func (h *Http) HookAll() { 17 | Hook(h.GetHook()) 18 | } 19 | 20 | func (h *Http) UnHookAll() { 21 | UnHook(h.GetHook()) 22 | } 23 | -------------------------------------------------------------------------------- /hook/httpRouter.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type HttpRouter struct { 4 | } 5 | 6 | func (h *HttpRouter) GetHook() []string { 7 | return []string{ 8 | "httpRouter", 9 | "httpRequestFormValue", 10 | "httpRequestCookie", 11 | "urlURLQuery", 12 | } 13 | } 14 | 15 | func (h *HttpRouter) HookAll() { 16 | Hook(h.GetHook()) 17 | } 18 | 19 | func (h *HttpRouter) UnHookAll() { 20 | UnHook(h.GetHook()) 21 | } 22 | -------------------------------------------------------------------------------- /hook/kafkaGo.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type KafkaGo struct { 4 | } 5 | 6 | func (g *KafkaGo) GetHook() []string { 7 | return []string{ 8 | "kafkaGoWriter", 9 | } 10 | } 11 | 12 | func (g *KafkaGo) HookAll() { 13 | Hook(g.GetHook()) 14 | } 15 | 16 | func (g *KafkaGo) UnHookAll() { 17 | UnHook(g.GetHook()) 18 | } 19 | -------------------------------------------------------------------------------- /hook/mux.go: -------------------------------------------------------------------------------- 1 | package hook 2 | 3 | type Mux struct { 4 | } 5 | 6 | func (h *Mux) GetHook() []string { 7 | return []string{ 8 | "muxServeHTTP", 9 | } 10 | } 11 | 12 | func (h *Mux) HookAll() { 13 | Hook(h.GetHook()) 14 | } 15 | 16 | func (h *Mux) UnHookAll() { 17 | UnHook(h.GetHook()) 18 | } 19 | -------------------------------------------------------------------------------- /model/config.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | type Config struct { 4 | DongtaiGoOpenapi string `yaml:"DongtaiGoOpenapi"` 5 | DongtaiGoToken string `yaml:"DongtaiGoToken"` 6 | DongtaiGoProjectName string `yaml:"DongtaiGoProjectName"` 7 | DongtaiGoProjectVersion string `yaml:"DongtaiGoProjectVersion"` 8 | DongtaiGoProjectCreate bool `yaml:"DongtaiGoProjectCreate"` 9 | DongtaiGoProjectGroupId int `yaml:"DongtaiGoProjectGroupId"` 10 | DongtaiGoProjectTemplateId int `yaml:"DongtaiGoProjectTemplateId"` 11 | } 12 | -------------------------------------------------------------------------------- /model/hook_base.go: -------------------------------------------------------------------------------- 1 | package model 2 | 3 | //定义的方法接口 后续更多功能 最好是嵌套接口 4 | type HookFunc interface { 5 | Hook() 6 | UnHook() 7 | } 8 | 9 | // 接口扩展时期示例 不影响原有功能 10 | type More interface { 11 | HookFunc 12 | More() 13 | } 14 | 15 | //实现一个方法调用的接口集合 用于对各类hook的统一map管理 动态挂载卸载 16 | var HookMap = make(map[string]HookFunc) 17 | 18 | type HookStruct interface { 19 | GetHook() []string 20 | HookAll() 21 | UnHookAll() 22 | } 23 | -------------------------------------------------------------------------------- /model/request/engine.go: -------------------------------------------------------------------------------- 1 | package request 2 | 3 | import ( 4 | "fmt" 5 | "reflect" 6 | "strconv" 7 | 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/utils" 10 | ) 11 | 12 | type AgentRegisterReq struct { 13 | AutoCreateProject bool `json:"autoCreateProject"` 14 | Name string `json:"name"` 15 | Language string `json:"language"` 16 | Version string `json:"version"` 17 | ProjectName string `json:"projectName"` 18 | Hostname string `json:"hostname"` 19 | Network string `json:"network"` 20 | ContainerName string `json:"containerName"` 21 | ContainerVersion string `json:"containerVersion"` 22 | ServerAddr string `json:"serverAddr"` 23 | ServerPort string `json:"serverPort"` 24 | ServerPath string `json:"serverPath"` 25 | ServerEnv string `json:"serverEnv"` 26 | Pid string `json:"pid"` 27 | ProjectVersion string `json:"projectVersion"` 28 | ProjectGroupId int `json:"projectGroupId"` 29 | ProjectTemplateId int `json:"projectTemplateId"` 30 | } 31 | 32 | type HookRuleReq struct { 33 | Language string `json:"language"` 34 | } 35 | 36 | // UploadReq 37 | /* Type 38 | 数据类型,可选择: 39 | 1 - Agent心跳数据 40 | 17 - 依赖组件数据 41 | 36 - 方法调用数据 42 | */ 43 | type UploadReq struct { 44 | Type int `json:"type"` 45 | Detail Detail `json:"detail"` 46 | InvokeId int `json:"invokeId"` 47 | } 48 | 49 | type Detail struct { 50 | AgentId int `json:"agentId"` 51 | Pant 52 | Component 53 | Components 54 | Function 55 | Pool 56 | Log 57 | Api 58 | } 59 | 60 | type Pant struct { 61 | Disk string `json:"disk"` 62 | Memory string `json:"memory"` 63 | Cpu string `json:"cpu"` 64 | MethodQueue int `json:"methodQueue"` 65 | ReplayQueue int `json:"replayQueue"` 66 | ReqCount int `json:"reqCount"` 67 | ReportQueue int `json:"reportQueue"` 68 | IsCoreInstalled int `json:"isCoreInstalled"` 69 | IsCoreRunning int `json:"isCoreRunning"` 70 | } 71 | 72 | type Component struct { 73 | PackagePath string `json:"packagePath"` 74 | PackageVersion string `json:"packageVersion"` 75 | PackageSignature string `json:"packageSignature"` 76 | PackageName string `json:"packageName"` 77 | PackageAlgorithm string `json:"packageAlgorithm"` 78 | } 79 | 80 | type Components struct { 81 | Packages []Component `json:"packages"` 82 | } 83 | 84 | type Function struct { 85 | Uri string `json:"uri"` 86 | Url string `json:"url"` 87 | Protocol string `json:"protocol"` 88 | ContextPath string `json:"contextPath"` 89 | Pool []Pool `json:"pool"` 90 | Language string `json:"language"` 91 | ClientIp string `json:"clientIp"` 92 | Secure bool `json:"secure"` 93 | QueryString string `json:"queryString"` 94 | ReplayRequest bool `json:"replayRequest"` 95 | Method string `json:"method"` 96 | ReqHeader string `json:"reqHeader"` 97 | ReqBody string `json:"reqBody"` 98 | ResBody string `json:"resBody"` 99 | Scheme string `json:"scheme"` 100 | ResHeader string `json:"resHeader"` 101 | TraceId string `json:"traceId"` 102 | } 103 | 104 | type Pool struct { 105 | InvokeId int `json:"invokeId"` 106 | Interfaces []interface{} `json:"interfaces"` 107 | TargetHash []string `json:"targetHash"` 108 | TargetValues string `json:"targetValues"` 109 | Signature string `json:"signature"` 110 | OriginClassName string `json:"originClassName"` 111 | SourceValues string `json:"sourceValues"` 112 | MethodName string `json:"methodName"` 113 | ClassName string `json:"className"` 114 | Source bool `json:"source"` 115 | CallerLineNumber int `json:"callerLineNumber"` 116 | CallerClass string `json:"callerClass"` 117 | Args string `json:"args"` 118 | CallerMethod string `json:"callerMethod"` 119 | SourceHash []string `json:"sourceHash"` 120 | RetClassName string `json:"retClassName"` 121 | TraceId string `json:"traceId"` 122 | Plugin string `json:"plugin"` 123 | } 124 | 125 | type PoolReq struct { 126 | Source bool 127 | OriginClassName string 128 | MethodName string 129 | ClassName string 130 | Args []interface{} 131 | Reqs []interface{} 132 | NeedHook []interface{} 133 | NeedCatch []interface{} 134 | ArgsStr string 135 | TraceId string 136 | Plugin string 137 | } 138 | 139 | type Log struct { 140 | Log string `json:"log"` 141 | } 142 | 143 | type Api struct { 144 | ApiData []ApiData `json:"apiData"` 145 | } 146 | 147 | type ApiData struct { 148 | Uri string `json:"uri"` 149 | Method []string `json:"method"` 150 | Class string `json:"class"` 151 | Parameters []Parameter `json:"parameters"` 152 | ReturnType string `json:"returnType"` 153 | File string `json:"file"` 154 | Controller string `json:"controller"` 155 | Description string `json:"description"` 156 | } 157 | 158 | type Parameter struct { 159 | Name string `json:"name"` 160 | Type string `json:"type"` 161 | Annotation string `json:"annotation"` 162 | } 163 | 164 | type PoolTree struct { 165 | *Pool 166 | Begin bool 167 | GoroutineID string 168 | Children []*PoolTree 169 | } 170 | 171 | func (p *PoolTree) IsThisBegin(GoroutineID string) bool { 172 | return GoroutineID == p.GoroutineID && p.Begin 173 | } 174 | 175 | func (p *PoolTree) FMT(pools *[]Pool, w *utils.Worker, goroutineIDs map[string]bool, TraceId string) { 176 | p.Pool.InvokeId = int(w.GetId()) 177 | // if(p.Pool.ClassName == "grpc.(*ClientConn)"){ 178 | // p.Pool.TraceId = TraceId 179 | // } 180 | *pools = append(*pools, *p.Pool) 181 | goroutineIDs[p.GoroutineID] = true 182 | fmt.Println(p.Pool.ClassName, p.Pool.MethodName) 183 | fmt.Println(p.Pool.SourceValues, "====>", p.Pool.TargetValues) 184 | fmt.Println(p.Pool.SourceHash, "===>", p.Pool.TargetHash) 185 | for k, v := range p.Children { 186 | global.PoolTreeMap.Delete(&v.Pool.TargetHash) 187 | p.Children[k].FMT(pools, w, goroutineIDs, TraceId) 188 | } 189 | } 190 | 191 | func Collect(args ...interface{}) []interface{} { 192 | return args 193 | } 194 | 195 | func FmtHookPool(p PoolReq) Pool { 196 | signature, callerClass, callerMethod, callerLineNumber := utils.FmtStack() 197 | var sourceHash global.HashKeys = make(global.HashKeys, 0) 198 | var SourceValues string = "" 199 | if len(p.NeedHook) == 0 { 200 | utils.RangeSource(p.Args, &p.NeedHook) 201 | } 202 | for _, v := range p.NeedHook { 203 | switch v.(type) { 204 | case string: 205 | sourceHash = append(sourceHash, utils.GetSource(v)) 206 | SourceValues = utils.StringAdd(SourceValues, v.(string), " ") 207 | break 208 | case uintptr: 209 | sourceHash = append(sourceHash, strconv.Itoa(int(v.(uintptr)))) 210 | SourceValues = utils.StringAdd(SourceValues, strconv.Itoa(int(v.(uintptr))), " ") 211 | break 212 | default: 213 | t := reflect.TypeOf(v) 214 | value := reflect.ValueOf(v) 215 | if t.Kind() == reflect.String { 216 | sourceHash = append(sourceHash, utils.GetSource(value.String())) 217 | SourceValues = utils.StringAdd(SourceValues, value.String(), " ") 218 | } 219 | break 220 | } 221 | } 222 | var targetHash global.HashKeys = make(global.HashKeys, 0) 223 | var targetValues string = "" 224 | var RetClassNames string = "" 225 | if len(p.NeedCatch) == 0 { 226 | utils.RangeSource(p.Reqs, &p.NeedCatch) 227 | } 228 | for _, v := range p.Reqs { 229 | if reflect.ValueOf(v).IsValid() { 230 | RetClassNames = utils.StringAdd(RetClassNames, reflect.ValueOf(v).Type().String(), " ") 231 | } 232 | } 233 | for _, v := range p.NeedCatch { 234 | switch v.(type) { 235 | case string: 236 | targetHash = append(targetHash, utils.GetSource(v)) 237 | targetValues = utils.StringAdd(targetValues, v.(string), " ") 238 | case uintptr: 239 | targetHash = append(targetHash, strconv.Itoa(int(v.(uintptr)))) 240 | targetValues = utils.StringAdd(targetValues, strconv.Itoa(int(v.(uintptr))), " ") 241 | } 242 | } 243 | var ArgsStr string 244 | if p.ArgsStr != "" { 245 | ArgsStr = p.ArgsStr 246 | } else { 247 | ArgsStr = utils.Strval(p.Args) 248 | } 249 | var pool = Pool{ 250 | Source: p.Source, 251 | Interfaces: []interface{}{}, 252 | SourceValues: SourceValues, 253 | SourceHash: sourceHash, 254 | TargetValues: targetValues, 255 | TargetHash: targetHash, 256 | Signature: signature, 257 | OriginClassName: p.OriginClassName, 258 | MethodName: p.MethodName, 259 | ClassName: p.ClassName, 260 | CallerLineNumber: callerLineNumber, 261 | CallerClass: callerClass, 262 | CallerMethod: callerMethod, 263 | RetClassName: RetClassNames, 264 | Args: ArgsStr, 265 | TraceId: p.TraceId, 266 | Plugin: p.Plugin, 267 | } 268 | 269 | poolTree := PoolTree{ 270 | Begin: p.Source, 271 | Pool: &pool, 272 | Children: []*PoolTree{}, 273 | GoroutineID: utils.CatGoroutineID(), 274 | } 275 | 276 | if !p.Source { 277 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 278 | if key.(*global.HashKeys).Some(sourceHash) { 279 | poolTree.GoroutineID = value.(*PoolTree).GoroutineID 280 | value.(*PoolTree).Children = append(value.(*PoolTree).Children, &poolTree) 281 | global.PoolTreeMap.Store(&targetHash, &poolTree) 282 | } 283 | return true 284 | }) 285 | } else { 286 | global.PoolTreeMap.Store(&targetHash, &poolTree) 287 | } 288 | return pool 289 | } 290 | 291 | func RunMapGCbYGoroutineID(goroutineIDs map[string]bool) { 292 | global.PoolTreeMap.Range(func(key, value interface{}) bool { 293 | for id, _ := range goroutineIDs { 294 | if value.(*PoolTree).GoroutineID == id { 295 | global.PoolTreeMap.Delete(key) 296 | } 297 | } 298 | return true 299 | }) 300 | } 301 | -------------------------------------------------------------------------------- /model/response/engine.go: -------------------------------------------------------------------------------- 1 | package response 2 | 3 | type ResBase struct { 4 | Status int `json:"status"` 5 | Msg string `json:"msg"` 6 | } 7 | 8 | type AgentRegisterRes struct { 9 | ResBase 10 | Data struct { 11 | Id int `json:"id"` 12 | CoreAutoStart int `json:"coreAutoStart"` 13 | } `json:"data"` 14 | } 15 | 16 | type LimitRes struct { 17 | ResBase 18 | Data []struct { 19 | Id int `json:"id"` 20 | Key string `json:"key"` 21 | Value string `json:"value"` 22 | } `json:"data"` 23 | } 24 | -------------------------------------------------------------------------------- /run/base/base.go: -------------------------------------------------------------------------------- 1 | package base 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/bufioWriterWrite" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/bufioWriterWriteString" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/execCmdStart" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/execCommand" 8 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/fmtSprintf" 9 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/htmlTemplateExecuteTemplate" 10 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/httpClientDo" 11 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/httpNewRequest" 12 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/ioReadAll" 13 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/jsonDecoderDecode" 14 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/jsonNewDecoder" 15 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/jsonUnmarshal" 16 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/osOpenFile" 17 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/regexpRegexpReplaceAllString" 18 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/runtimeConcatstrings" 19 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/runtimesSringtoslicebyte" 20 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/sqlDBQuery" 21 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/stringsBuilderWriteString" 22 | _ "github.com/HXSecurity/DongTai-agent-go/core/base/urlUrlString" 23 | "github.com/HXSecurity/DongTai-agent-go/hook" 24 | "github.com/HXSecurity/DongTai-agent-go/service" 25 | "github.com/HXSecurity/DongTai-agent-go/utils" 26 | "strconv" 27 | 28 | "github.com/HXSecurity/DongTai-agent-go/global" 29 | ) 30 | 31 | func init() { 32 | b := new(hook.Base) 33 | global.AllHooks = append(global.AllHooks, b) 34 | global.InitViper() 35 | _ = service.AgentRegister() 36 | b.HookAll() 37 | worker, _ := utils.NewWorker(global.AgentId) 38 | global.TraceId = strconv.Itoa(int(worker.GetId())) 39 | } 40 | -------------------------------------------------------------------------------- /run/chiRouter/hookChiRouter.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestCookie" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestFormValue" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/urlURLQuery" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/httpRouter/httpRouter" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/hook" 10 | ) 11 | 12 | func init() { 13 | h := new(hook.ChiRouter) 14 | global.AllHooks = append(global.AllHooks, h) 15 | h.HookAll() 16 | } 17 | -------------------------------------------------------------------------------- /run/gin/hookGin.go: -------------------------------------------------------------------------------- 1 | package gin 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextGetPostFormArray" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextGetPostFormMap" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextGetQueryArray" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextGetQueryMap" 8 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextParam" 9 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextShouldBindBodyWith" 10 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextShouldBindUri" 11 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginContextShouldBindWith" 12 | _ "github.com/HXSecurity/DongTai-agent-go/core/gin/ginEngineServerHTTP" 13 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestCookie" 14 | "github.com/HXSecurity/DongTai-agent-go/global" 15 | "github.com/HXSecurity/DongTai-agent-go/hook" 16 | ) 17 | 18 | func init() { 19 | g := new(hook.Gin) 20 | global.AllHooks = append(global.AllHooks, g) 21 | g.HookAll() 22 | } 23 | -------------------------------------------------------------------------------- /run/gorilla/hookGorilla.go: -------------------------------------------------------------------------------- 1 | package gorilla 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorilla/gorillaRpcServerHTTP" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/hook" 7 | ) 8 | 9 | func init() { 10 | g := new(hook.Gorilla) 11 | global.AllHooks = append(global.AllHooks, g) 12 | g.HookAll() 13 | } 14 | -------------------------------------------------------------------------------- /run/gorm/hookGorm.go: -------------------------------------------------------------------------------- 1 | package gorm 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBExec" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBGroup" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBHaving" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBOrder" 8 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBPluck" 9 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBRaw" 10 | _ "github.com/HXSecurity/DongTai-agent-go/core/gorm/gormDBSelect" 11 | "github.com/HXSecurity/DongTai-agent-go/global" 12 | "github.com/HXSecurity/DongTai-agent-go/hook" 13 | ) 14 | 15 | func init() { 16 | g := new(hook.Gorm) 17 | global.AllHooks = append(global.AllHooks, g) 18 | g.HookAll() 19 | } 20 | -------------------------------------------------------------------------------- /run/grpc/grpc.go: -------------------------------------------------------------------------------- 1 | package grpc 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/grpc/clientConn" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/grpc/newServer" 6 | "github.com/HXSecurity/DongTai-agent-go/global" 7 | "github.com/HXSecurity/DongTai-agent-go/hook" 8 | ) 9 | 10 | func init() { 11 | g := new(hook.Grpc) 12 | global.AllHooks = append(global.AllHooks, g) 13 | g.HookAll() 14 | } 15 | -------------------------------------------------------------------------------- /run/http/hookHttp.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpHeaderGet" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestCookie" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestFormValue" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpServeHTTP" 8 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/urlURLQuery" 9 | "github.com/HXSecurity/DongTai-agent-go/global" 10 | "github.com/HXSecurity/DongTai-agent-go/hook" 11 | ) 12 | 13 | func init() { 14 | h := new(hook.Http) 15 | global.AllHooks = append(global.AllHooks, h) 16 | h.HookAll() 17 | } 18 | -------------------------------------------------------------------------------- /run/httpRouter/hookHttpRouter.go: -------------------------------------------------------------------------------- 1 | package httpRouter 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestCookie" 5 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/httpRequestFormValue" 6 | _ "github.com/HXSecurity/DongTai-agent-go/core/http/urlURLQuery" 7 | _ "github.com/HXSecurity/DongTai-agent-go/core/httpRouter/httpRouter" 8 | "github.com/HXSecurity/DongTai-agent-go/global" 9 | "github.com/HXSecurity/DongTai-agent-go/hook" 10 | ) 11 | 12 | func init() { 13 | h := new(hook.HttpRouter) 14 | global.AllHooks = append(global.AllHooks, h) 15 | h.HookAll() 16 | } 17 | -------------------------------------------------------------------------------- /run/kafkaGo/kafkaGo.go: -------------------------------------------------------------------------------- 1 | package kafkaGo 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/kafkaGo/kafkaWriter" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/hook" 7 | ) 8 | 9 | func init() { 10 | g := new(hook.KafkaGo) 11 | global.AllHooks = append(global.AllHooks, g) 12 | g.HookAll() 13 | } 14 | -------------------------------------------------------------------------------- /run/mux/hookMux.go: -------------------------------------------------------------------------------- 1 | package http 2 | 3 | import ( 4 | _ "github.com/HXSecurity/DongTai-agent-go/core/mux/muxServerHTTP" 5 | "github.com/HXSecurity/DongTai-agent-go/global" 6 | "github.com/HXSecurity/DongTai-agent-go/hook" 7 | ) 8 | 9 | func init() { 10 | h := new(hook.Mux) 11 | global.AllHooks = append(global.AllHooks, h) 12 | h.HookAll() 13 | } 14 | -------------------------------------------------------------------------------- /service/auxiliarygt18.go: -------------------------------------------------------------------------------- 1 | //go:build go1.18 2 | // +build go1.18 3 | 4 | package service 5 | 6 | import ( 7 | "debug/buildinfo" 8 | "fmt" 9 | "github.com/HXSecurity/DongTai-agent-go/model/request" 10 | "github.com/HXSecurity/DongTai-agent-go/utils" 11 | "github.com/pkg/errors" 12 | "io/fs" 13 | "os" 14 | "os/exec" 15 | "path/filepath" 16 | "runtime" 17 | "strings" 18 | ) 19 | 20 | // GenAQLForGolang 为golang组件生成aql 21 | func GenAQLForGolang(packageName, version string) string { 22 | return fmt.Sprintf("golang:%s:%s:", packageName, version) 23 | } 24 | 25 | // 获取包 26 | func GetMod() ([]request.Component, string) { 27 | //fmt.Println(getCurrentPath()) 28 | path, _ := os.Executable() 29 | return scanFile(path, true) 30 | } 31 | 32 | // 判断是否是exe文件 33 | func isExe(file string, info fs.FileInfo) bool { 34 | if runtime.GOOS == "windows" { 35 | return strings.HasSuffix(strings.ToLower(file), ".exe") 36 | } 37 | return info.Mode().IsRegular() && info.Mode()&0111 != 0 38 | } 39 | 40 | // 从二进制文件读取包信息 41 | func scanFile(file string, mustPrint bool) (packages []request.Component, agentVersion string) { 42 | bi, err := buildinfo.ReadFile(file) 43 | if err != nil { 44 | if mustPrint { 45 | if pathErr := (*os.PathError)(nil); errors.As(err, &pathErr) && filepath.Clean(pathErr.Path) == filepath.Clean(file) { 46 | fmt.Fprintf(os.Stderr, "%v\n", file) 47 | } else { 48 | fmt.Fprintf(os.Stderr, "%s: %v\n", file, err) 49 | } 50 | } 51 | return packages, agentVersion 52 | } 53 | fmt.Printf("%s: %s\n", file, bi.GoVersion) 54 | bi.GoVersion = "" // suppress printing go version again 55 | mod := bi.String() 56 | 57 | li := strings.Split(mod[:len(mod)-1], "\n") 58 | for i := range li { 59 | licl := strings.Split(li[i], "\t") 60 | if licl[0] == "dep" { 61 | fmt.Printf("依赖:%s\t版本:%s\n", licl[1], licl[2]) 62 | aql := GenAQLForGolang(licl[1], licl[2]) 63 | if licl[1] == "github.com/HXSecurity/DongTai-agent-go" { 64 | fmt.Println("当前探针版本为:" + licl[2]) 65 | agentVersion = licl[2] 66 | } 67 | packages = append(packages, request.Component{ 68 | PackageName: aql, 69 | PackageAlgorithm: "SHA-1", 70 | PackagePath: file, 71 | PackageVersion: licl[2], 72 | PackageSignature: utils.SHA1(aql), 73 | }, 74 | ) 75 | } 76 | } 77 | return packages, agentVersion 78 | } 79 | 80 | // 获取服务信息 81 | func getServerInfo() (server *utils.Server, err error) { 82 | var s utils.Server 83 | s.Os = utils.InitOS() 84 | if s.Cpu, err = utils.InitCPU(); err != nil { 85 | fmt.Println(err.Error()) 86 | return &s, err 87 | } 88 | if s.Rrm, err = utils.InitRAM(); err != nil { 89 | fmt.Println(err.Error()) 90 | return &s, err 91 | } 92 | if s.Disk, err = utils.InitDisk(); err != nil { 93 | fmt.Println(err.Error()) 94 | return &s, err 95 | } 96 | 97 | return &s, nil 98 | } 99 | 100 | func getCurrentPath() (string, error) { 101 | file, err := exec.LookPath(os.Args[0]) 102 | if err != nil { 103 | return "", err 104 | } 105 | path, err := filepath.Abs(file) 106 | if err != nil { 107 | return "", err 108 | } 109 | i := strings.LastIndex(path, "/") 110 | if i < 0 { 111 | i = strings.LastIndex(path, "\\") 112 | } 113 | if i < 0 { 114 | return "", errors.New(`error: Can't find "/" or "\".`) 115 | } 116 | return string(path[0 : i+1]), nil 117 | } 118 | -------------------------------------------------------------------------------- /service/auxiliarylt18.go: -------------------------------------------------------------------------------- 1 | //go:build !go1.18 2 | // +build !go1.18 3 | 4 | package service 5 | 6 | import ( 7 | "bytes" 8 | "encoding/binary" 9 | "fmt" 10 | "github.com/HXSecurity/DongTai-agent-go/model/request" 11 | "github.com/HXSecurity/DongTai-agent-go/service/version" 12 | "github.com/HXSecurity/DongTai-agent-go/utils" 13 | "github.com/pkg/errors" 14 | "io/fs" 15 | "os" 16 | "os/exec" 17 | "path/filepath" 18 | "runtime" 19 | "strings" 20 | ) 21 | 22 | var buildInfoMagic = []byte("\xff Go buildinf:") 23 | 24 | // An exe is a generic interface to an OS executable (ELF, Mach-O, PE, XCOFF). 25 | type exe interface { 26 | // Close closes the underlying file. 27 | Close() error 28 | 29 | // ReadData reads and returns up to size byte starting at virtual address addr. 30 | ReadData(addr, size uint64) ([]byte, error) 31 | 32 | // DataStart returns the writable data segment start address. 33 | DataStart() uint64 34 | } 35 | 36 | // GenAQLForGolang 为golang组件生成aql 37 | func GenAQLForGolang(packageName, version string) string { 38 | return fmt.Sprintf("golang:%s:%s:", packageName, version) 39 | } 40 | 41 | // 获取包 42 | func GetMod() ([]request.Component, string) { 43 | //fmt.Println(getCurrentPath()) 44 | path, _ := os.Executable() 45 | return scanFile(path, true) 46 | } 47 | 48 | // 判断是否是exe文件 49 | func isExe(file string, info fs.FileInfo) bool { 50 | if runtime.GOOS == "windows" { 51 | return strings.HasSuffix(strings.ToLower(file), ".exe") 52 | } 53 | return info.Mode().IsRegular() && info.Mode()&0111 != 0 54 | } 55 | 56 | // 从二进制文件读取包信息 57 | func scanFile(file string, mustPrint bool) (packages []request.Component, agentVersion string) { 58 | 59 | i, err := os.Stat(file) 60 | info := i 61 | 62 | if !isExe(file, info) { 63 | if mustPrint { 64 | fmt.Fprintf(os.Stderr, "%s: not executable file\n", file) 65 | } 66 | return 67 | } 68 | 69 | x, err := version.OpenExe(file) 70 | if err != nil { 71 | if mustPrint { 72 | fmt.Fprintf(os.Stderr, "%s: %v\n", file, err) 73 | } 74 | return 75 | } 76 | defer x.Close() 77 | 78 | vers, mod := findVers(x) 79 | if vers == "" { 80 | if mustPrint { 81 | fmt.Fprintf(os.Stderr, "%s: go version not found\n", file) 82 | } 83 | return 84 | } 85 | 86 | li := strings.Split(mod[:len(mod)-1], "\n") 87 | for i := range li { 88 | licl := strings.Split(li[i], "\t") 89 | if licl[0] == "dep" { 90 | fmt.Printf("依赖:%s\t版本:%s\n", licl[1], licl[2]) 91 | aql := GenAQLForGolang(licl[1], licl[2]) 92 | if licl[1] == "github.com/HXSecurity/DongTai-agent-go" { 93 | fmt.Println("当前探针版本为:" + licl[2]) 94 | agentVersion = licl[2] 95 | } 96 | packages = append(packages, request.Component{ 97 | PackageName: aql, 98 | PackageAlgorithm: "SHA-1", 99 | PackagePath: file, 100 | PackageVersion: licl[2], 101 | PackageSignature: utils.SHA1(aql), 102 | }, 103 | ) 104 | } 105 | } 106 | return packages, agentVersion 107 | } 108 | 109 | // 获取服务信息 110 | func getServerInfo() (server *utils.Server, err error) { 111 | var s utils.Server 112 | s.Os = utils.InitOS() 113 | if s.Cpu, err = utils.InitCPU(); err != nil { 114 | fmt.Println(err.Error()) 115 | return &s, err 116 | } 117 | if s.Rrm, err = utils.InitRAM(); err != nil { 118 | fmt.Println(err.Error()) 119 | return &s, err 120 | } 121 | if s.Disk, err = utils.InitDisk(); err != nil { 122 | fmt.Println(err.Error()) 123 | return &s, err 124 | } 125 | 126 | return &s, nil 127 | } 128 | 129 | func getCurrentPath() (string, error) { 130 | file, err := exec.LookPath(os.Args[0]) 131 | if err != nil { 132 | return "", err 133 | } 134 | path, err := filepath.Abs(file) 135 | if err != nil { 136 | return "", err 137 | } 138 | i := strings.LastIndex(path, "/") 139 | if i < 0 { 140 | i = strings.LastIndex(path, "\\") 141 | } 142 | if i < 0 { 143 | return "", errors.New(`error: Can't find "/" or "\".`) 144 | } 145 | return string(path[0 : i+1]), nil 146 | } 147 | 148 | func findVers(x exe) (vers, mod string) { 149 | // Read the first 64kB of text to find the build info blob. 150 | text := x.DataStart() 151 | data, err := x.ReadData(text, 64*1024) 152 | if err != nil { 153 | return 154 | } 155 | for ; !bytes.HasPrefix(data, buildInfoMagic); data = data[32:] { 156 | if len(data) < 32 { 157 | return 158 | } 159 | } 160 | 161 | // Decode the blob. 162 | ptrSize := int(data[14]) 163 | bigEndian := data[15] != 0 164 | var bo binary.ByteOrder 165 | if bigEndian { 166 | bo = binary.BigEndian 167 | } else { 168 | bo = binary.LittleEndian 169 | } 170 | var readPtr func([]byte) uint64 171 | if ptrSize == 4 { 172 | readPtr = func(b []byte) uint64 { return uint64(bo.Uint32(b)) } 173 | } else { 174 | readPtr = bo.Uint64 175 | } 176 | vers = readString(x, ptrSize, readPtr, readPtr(data[16:])) 177 | if vers == "" { 178 | return 179 | } 180 | mod = readString(x, ptrSize, readPtr, readPtr(data[16+ptrSize:])) 181 | if len(mod) >= 33 && mod[len(mod)-17] == '\n' { 182 | // Strip module framing. 183 | mod = mod[16 : len(mod)-16] 184 | } else { 185 | mod = "" 186 | } 187 | return 188 | } 189 | 190 | // readString returns the string at address addr in the executable x. 191 | func readString(x exe, ptrSize int, readPtr func([]byte) uint64, addr uint64) string { 192 | hdr, err := x.ReadData(addr, uint64(2*ptrSize)) 193 | if err != nil || len(hdr) < 2*ptrSize { 194 | return "" 195 | } 196 | dataAddr := readPtr(hdr) 197 | dataLen := readPtr(hdr[ptrSize:]) 198 | data, err := x.ReadData(dataAddr, dataLen) 199 | if err != nil || uint64(len(data)) < dataLen { 200 | return "" 201 | } 202 | return string(data) 203 | } 204 | -------------------------------------------------------------------------------- /service/engine.go: -------------------------------------------------------------------------------- 1 | package service 2 | 3 | import ( 4 | "bytes" 5 | "encoding/base64" 6 | "encoding/json" 7 | "fmt" 8 | "os/exec" 9 | "regexp" 10 | "strconv" 11 | "strings" 12 | "time" 13 | 14 | "github.com/HXSecurity/DongTai-agent-go/api" 15 | "github.com/HXSecurity/DongTai-agent-go/global" 16 | "github.com/HXSecurity/DongTai-agent-go/hook" 17 | "github.com/HXSecurity/DongTai-agent-go/utils" 18 | "net" 19 | "os" 20 | "runtime" 21 | 22 | // "github.com/HXSecurity/DongTai-agent-go/api" 23 | "github.com/HXSecurity/DongTai-agent-go/model/request" 24 | ) 25 | 26 | var live bool 27 | 28 | func CreateCircuitBreaker() func() (err error) { 29 | var count int 30 | var circuit bool 31 | return func() (err error) { 32 | limit := api.Limit() 33 | cpuLimit, ferr := strconv.ParseFloat(limit["cpu_limit"], 32) 34 | if ferr != nil || cpuLimit == 0 { 35 | cpuLimit = 100 36 | return 37 | } 38 | s, err := getServerInfo() 39 | var cpuNum float64 40 | cpus := s.Cpu.Cpus 41 | for _, k := range cpus { 42 | cpuNum += k 43 | } 44 | cpu := cpuNum / float64(len(cpus)) 45 | if cpu > cpuLimit { 46 | if count >= 5 { 47 | circuit = true 48 | count = 0 49 | StopAgent() 50 | return 51 | } 52 | count++ 53 | } 54 | if cpu <= cpuLimit { 55 | count = 0 56 | if circuit { 57 | RunAgent() 58 | } 59 | } 60 | return nil 61 | } 62 | } 63 | 64 | func StopAgent() { 65 | live = false 66 | hook.HookAll(global.AllHooks...) 67 | } 68 | 69 | func RunAgent() { 70 | live = true 71 | hook.UnHookAll(global.AllHooks...) 72 | } 73 | 74 | func AgentRegister() (err error) { 75 | max := 6 76 | breaker := CreateCircuitBreaker() 77 | live = true 78 | OS := runtime.GOOS 79 | hostname, _ := os.Hostname() 80 | version := "1.0.0" 81 | packages, agentVersion := GetMod() 82 | if global.Config.DongtaiGoProjectVersion != "" { 83 | version = global.Config.DongtaiGoProjectVersion 84 | } 85 | projectName := "project Name" 86 | if global.Config.DongtaiGoProjectVersion != "" { 87 | projectName = global.Config.DongtaiGoProjectName 88 | } 89 | name := OS + "-" + hostname + "-" + version 90 | interfaces, err := net.Interfaces() 91 | if err != nil { 92 | return 93 | } 94 | 95 | ips := "" 96 | 97 | for _, i := range interfaces { 98 | byName, err := net.InterfaceByName(i.Name) 99 | if err != nil { 100 | return err 101 | } 102 | addresses, err := byName.Addrs() 103 | for _, v := range addresses { 104 | if ips == "" { 105 | ips = "{\"name\":" + byName.Name + ",\"ip\":" + v.String() + "}" 106 | } else { 107 | ips += ",{\"name\":" + byName.Name + ",\"ip\":" + v.String() + "}" 108 | } 109 | } 110 | } 111 | pid := os.Getpid() 112 | envMap := make(map[string]string) 113 | envs := os.Environ() 114 | for _, v := range envs { 115 | parts := strings.SplitN(v, "=", 2) 116 | if len(parts) != 2 { 117 | continue 118 | } else { 119 | envMap[parts[0]] = parts[1] 120 | } 121 | } 122 | envB, err := json.Marshal(envMap) 123 | if err != nil { 124 | return err 125 | } 126 | encodeEnv := base64.StdEncoding.EncodeToString(envB) 127 | 128 | filePath, err := getCurrentPath() 129 | if err != nil { 130 | return err 131 | } 132 | req := request.AgentRegisterReq{ 133 | AutoCreateProject: global.Config.DongtaiGoProjectCreate, 134 | Name: name, 135 | Language: "GO", 136 | Version: agentVersion, 137 | ProjectVersion: version, 138 | ProjectName: projectName, 139 | Hostname: hostname, 140 | Network: ips, 141 | ContainerName: "GO", 142 | ContainerVersion: "GO", 143 | ServerAddr: "", 144 | ServerPort: "", 145 | ServerPath: filePath, 146 | ServerEnv: encodeEnv, 147 | Pid: strconv.Itoa(pid), 148 | ProjectGroupId: global.Config.DongtaiGoProjectGroupId, 149 | ProjectTemplateId: global.Config.DongtaiGoProjectTemplateId, 150 | } 151 | go func() { 152 | for { 153 | max = max - 1 154 | fmt.Printf("等待当前程序当前程序启动完成,剩余%d次", max) 155 | time.Sleep(1 * time.Second) 156 | ip, err := utils.ExternalIP() 157 | if err != nil { 158 | fmt.Println(err) 159 | } 160 | var cmd *exec.Cmd 161 | var strErr bytes.Buffer 162 | var out bytes.Buffer 163 | if OS == "windows" { 164 | cmd = exec.Command("netstat", "-ano") 165 | cmd.Stderr = &strErr 166 | cmd.Stdout = &out 167 | } else { 168 | cmd = exec.Command("netstat", "-antup", "|grep", req.Pid) 169 | cmd.Stderr = &strErr 170 | cmd.Stdout = &out 171 | } 172 | fmt.Println("等待当前程序端口返回") 173 | err = cmd.Run() 174 | fmt.Println("等待当前程序端口返回成功") 175 | output := out.String() 176 | if err != nil { 177 | return 178 | } 179 | var matches [][]string 180 | if OS == "windows" { 181 | str := "" 182 | for { 183 | line, setErr := out.ReadBytes('\n') 184 | if setErr != nil { 185 | break 186 | } 187 | if strings.Index(string(line), " "+req.Pid) > -1 { 188 | str += string(line) + "\n" 189 | } 190 | } 191 | r := regexp.MustCompile(`0.0.0.0:\s*(.*?)\s* `) 192 | matches = r.FindAllStringSubmatch(str, -1) 193 | } else { 194 | r := regexp.MustCompile(`:::\s*(.*?)\s* `) 195 | matches = r.FindAllStringSubmatch(output, -1) 196 | } 197 | if matches != nil || max == 0 { 198 | if matches[0] != nil || max == 0 { 199 | if matches[0][1] != "" || max == 0 { 200 | fmt.Println("当前程序启动完成") 201 | if max == 0 { 202 | req.ServerPort = "" 203 | } else { 204 | req.ServerPort = matches[0][1] 205 | } 206 | req.ServerAddr = ip.String() 207 | agentId, err := api.AgentRegister(req) 208 | if err != nil { 209 | fmt.Println(err) 210 | break 211 | } 212 | global.AgentId = agentId 213 | UploadSca(packages) 214 | go func() { 215 | for { 216 | time.Sleep(10 * time.Second) 217 | PingPang() 218 | breaker() 219 | } 220 | }() 221 | break 222 | } 223 | } 224 | } 225 | 226 | } 227 | }() 228 | return nil 229 | } 230 | 231 | func PingPang() { 232 | s, err := getServerInfo() 233 | if err != nil { 234 | return 235 | } 236 | var req request.UploadReq 237 | cpuMap := make(map[string]string) 238 | memoryMap := make(map[string]string) 239 | var cpus float64 = 0 240 | for _, v := range s.Cpu.Cpus { 241 | cpus += v 242 | } 243 | cpuRate := fmt.Sprintf("%.2f", cpus/float64(len(s.Cpu.Cpus))) 244 | memoryRate := fmt.Sprintf("%.2f", float64(s.Rrm.UsedMB)/float64(s.Rrm.TotalMB)) 245 | total := strconv.Itoa(s.Rrm.TotalMB) + "MB" 246 | use := strconv.Itoa(s.Rrm.UsedMB) + "MB" 247 | cpuMap["rate"] = cpuRate 248 | memoryMap["total"] = total 249 | memoryMap["use"] = use 250 | memoryMap["rate"] = memoryRate 251 | cpuByte, _ := json.Marshal(cpuMap) 252 | memoryByte, _ := json.Marshal(memoryMap) 253 | 254 | req.Type = 1 255 | req.Detail.Pant.Disk = "{}" 256 | req.Detail.Pant.Cpu = string(cpuByte) 257 | req.Detail.Pant.Memory = string(memoryByte) 258 | req.Detail.Pant.IsCoreRunning = 1 259 | req.Detail.Pant.IsCoreInstalled = 1 260 | req.Detail.AgentId = global.AgentId 261 | api.ReportUpload(req) 262 | } 263 | func UploadSca(packages []request.Component) { 264 | var req request.UploadReq 265 | req.Type = 18 266 | req.Detail.AgentId = global.AgentId 267 | req.Detail.Packages = packages 268 | api.ReportUpload(req) 269 | } 270 | -------------------------------------------------------------------------------- /service/version/exe.go: -------------------------------------------------------------------------------- 1 | // Copyright 2019 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package version 6 | 7 | import ( 8 | "bytes" 9 | "debug/elf" 10 | "debug/macho" 11 | "debug/pe" 12 | "fmt" 13 | "github.com/HXSecurity/DongTai-agent-go/service/xcoff" 14 | "io" 15 | "os" 16 | ) 17 | 18 | // An exe is a generic interface to an OS executable (ELF, Mach-O, PE, XCOFF). 19 | type exe interface { 20 | // Close closes the underlying file. 21 | Close() error 22 | 23 | // ReadData reads and returns up to size byte starting at virtual address addr. 24 | ReadData(addr, size uint64) ([]byte, error) 25 | 26 | // DataStart returns the writable data segment start address. 27 | DataStart() uint64 28 | } 29 | 30 | // openExe opens file and returns it as an exe. 31 | func OpenExe(file string) (exe, error) { 32 | f, err := os.Open(file) 33 | if err != nil { 34 | return nil, err 35 | } 36 | data := make([]byte, 16) 37 | if _, err := io.ReadFull(f, data); err != nil { 38 | return nil, err 39 | } 40 | f.Seek(0, 0) 41 | if bytes.HasPrefix(data, []byte("\x7FELF")) { 42 | e, err := elf.NewFile(f) 43 | if err != nil { 44 | f.Close() 45 | return nil, err 46 | } 47 | return &elfExe{f, e}, nil 48 | } 49 | if bytes.HasPrefix(data, []byte("MZ")) { 50 | e, err := pe.NewFile(f) 51 | if err != nil { 52 | f.Close() 53 | return nil, err 54 | } 55 | return &peExe{f, e}, nil 56 | } 57 | if bytes.HasPrefix(data, []byte("\xFE\xED\xFA")) || bytes.HasPrefix(data[1:], []byte("\xFA\xED\xFE")) { 58 | e, err := macho.NewFile(f) 59 | if err != nil { 60 | f.Close() 61 | return nil, err 62 | } 63 | return &machoExe{f, e}, nil 64 | } 65 | if bytes.HasPrefix(data, []byte{0x01, 0xDF}) || bytes.HasPrefix(data, []byte{0x01, 0xF7}) { 66 | e, err := xcoff.NewFile(f) 67 | if err != nil { 68 | f.Close() 69 | return nil, err 70 | } 71 | return &xcoffExe{f, e}, nil 72 | 73 | } 74 | return nil, fmt.Errorf("unrecognized executable format") 75 | } 76 | 77 | // elfExe is the ELF implementation of the exe interface. 78 | type elfExe struct { 79 | os *os.File 80 | f *elf.File 81 | } 82 | 83 | func (x *elfExe) Close() error { 84 | return x.os.Close() 85 | } 86 | 87 | func (x *elfExe) ReadData(addr, size uint64) ([]byte, error) { 88 | for _, prog := range x.f.Progs { 89 | if prog.Vaddr <= addr && addr <= prog.Vaddr+prog.Filesz-1 { 90 | n := prog.Vaddr + prog.Filesz - addr 91 | if n > size { 92 | n = size 93 | } 94 | data := make([]byte, n) 95 | _, err := prog.ReadAt(data, int64(addr-prog.Vaddr)) 96 | if err != nil { 97 | return nil, err 98 | } 99 | return data, nil 100 | } 101 | } 102 | return nil, fmt.Errorf("address not mapped") 103 | } 104 | 105 | func (x *elfExe) DataStart() uint64 { 106 | for _, s := range x.f.Sections { 107 | if s.Name == ".go.buildinfo" { 108 | return s.Addr 109 | } 110 | } 111 | for _, p := range x.f.Progs { 112 | if p.Type == elf.PT_LOAD && p.Flags&(elf.PF_X|elf.PF_W) == elf.PF_W { 113 | return p.Vaddr 114 | } 115 | } 116 | return 0 117 | } 118 | 119 | // peExe is the PE (Windows Portable Executable) implementation of the exe interface. 120 | type peExe struct { 121 | os *os.File 122 | f *pe.File 123 | } 124 | 125 | func (x *peExe) Close() error { 126 | return x.os.Close() 127 | } 128 | 129 | func (x *peExe) imageBase() uint64 { 130 | switch oh := x.f.OptionalHeader.(type) { 131 | case *pe.OptionalHeader32: 132 | return uint64(oh.ImageBase) 133 | case *pe.OptionalHeader64: 134 | return oh.ImageBase 135 | } 136 | return 0 137 | } 138 | 139 | func (x *peExe) ReadData(addr, size uint64) ([]byte, error) { 140 | addr -= x.imageBase() 141 | for _, sect := range x.f.Sections { 142 | if uint64(sect.VirtualAddress) <= addr && addr <= uint64(sect.VirtualAddress+sect.Size-1) { 143 | n := uint64(sect.VirtualAddress+sect.Size) - addr 144 | if n > size { 145 | n = size 146 | } 147 | data := make([]byte, n) 148 | _, err := sect.ReadAt(data, int64(addr-uint64(sect.VirtualAddress))) 149 | if err != nil { 150 | return nil, err 151 | } 152 | return data, nil 153 | } 154 | } 155 | return nil, fmt.Errorf("address not mapped") 156 | } 157 | 158 | func (x *peExe) DataStart() uint64 { 159 | // Assume data is first writable section. 160 | const ( 161 | IMAGE_SCN_CNT_CODE = 0x00000020 162 | IMAGE_SCN_CNT_INITIALIZED_DATA = 0x00000040 163 | IMAGE_SCN_CNT_UNINITIALIZED_DATA = 0x00000080 164 | IMAGE_SCN_MEM_EXECUTE = 0x20000000 165 | IMAGE_SCN_MEM_READ = 0x40000000 166 | IMAGE_SCN_MEM_WRITE = 0x80000000 167 | IMAGE_SCN_MEM_DISCARDABLE = 0x2000000 168 | IMAGE_SCN_LNK_NRELOC_OVFL = 0x1000000 169 | IMAGE_SCN_ALIGN_32BYTES = 0x600000 170 | ) 171 | for _, sect := range x.f.Sections { 172 | if sect.VirtualAddress != 0 && sect.Size != 0 && 173 | sect.Characteristics&^IMAGE_SCN_ALIGN_32BYTES == IMAGE_SCN_CNT_INITIALIZED_DATA|IMAGE_SCN_MEM_READ|IMAGE_SCN_MEM_WRITE { 174 | return uint64(sect.VirtualAddress) + x.imageBase() 175 | } 176 | } 177 | return 0 178 | } 179 | 180 | // machoExe is the Mach-O (Apple macOS/iOS) implementation of the exe interface. 181 | type machoExe struct { 182 | os *os.File 183 | f *macho.File 184 | } 185 | 186 | func (x *machoExe) Close() error { 187 | return x.os.Close() 188 | } 189 | 190 | func (x *machoExe) ReadData(addr, size uint64) ([]byte, error) { 191 | for _, load := range x.f.Loads { 192 | seg, ok := load.(*macho.Segment) 193 | if !ok { 194 | continue 195 | } 196 | if seg.Addr <= addr && addr <= seg.Addr+seg.Filesz-1 { 197 | if seg.Name == "__PAGEZERO" { 198 | continue 199 | } 200 | n := seg.Addr + seg.Filesz - addr 201 | if n > size { 202 | n = size 203 | } 204 | data := make([]byte, n) 205 | _, err := seg.ReadAt(data, int64(addr-seg.Addr)) 206 | if err != nil { 207 | return nil, err 208 | } 209 | return data, nil 210 | } 211 | } 212 | return nil, fmt.Errorf("address not mapped") 213 | } 214 | 215 | func (x *machoExe) DataStart() uint64 { 216 | // Look for section named "__go_buildinfo". 217 | for _, sec := range x.f.Sections { 218 | if sec.Name == "__go_buildinfo" { 219 | return sec.Addr 220 | } 221 | } 222 | // Try the first non-empty writable segment. 223 | const RW = 3 224 | for _, load := range x.f.Loads { 225 | seg, ok := load.(*macho.Segment) 226 | if ok && seg.Addr != 0 && seg.Filesz != 0 && seg.Prot == RW && seg.Maxprot == RW { 227 | return seg.Addr 228 | } 229 | } 230 | return 0 231 | } 232 | 233 | // xcoffExe is the XCOFF (AIX eXtended COFF) implementation of the exe interface. 234 | type xcoffExe struct { 235 | os *os.File 236 | f *xcoff.File 237 | } 238 | 239 | func (x *xcoffExe) Close() error { 240 | return x.os.Close() 241 | } 242 | 243 | func (x *xcoffExe) ReadData(addr, size uint64) ([]byte, error) { 244 | for _, sect := range x.f.Sections { 245 | if uint64(sect.VirtualAddress) <= addr && addr <= uint64(sect.VirtualAddress+sect.Size-1) { 246 | n := uint64(sect.VirtualAddress+sect.Size) - addr 247 | if n > size { 248 | n = size 249 | } 250 | data := make([]byte, n) 251 | _, err := sect.ReadAt(data, int64(addr-uint64(sect.VirtualAddress))) 252 | if err != nil { 253 | return nil, err 254 | } 255 | return data, nil 256 | } 257 | } 258 | return nil, fmt.Errorf("address not mapped") 259 | } 260 | 261 | func (x *xcoffExe) DataStart() uint64 { 262 | return x.f.SectionByType(xcoff.STYP_DATA).VirtualAddress 263 | } 264 | -------------------------------------------------------------------------------- /service/xcoff/ar.go: -------------------------------------------------------------------------------- 1 | // Copyright 2018 The Go Authors. All rights reserved. 2 | // Use of this source code is governed by a BSD-style 3 | // license that can be found in the LICENSE file. 4 | 5 | package xcoff 6 | 7 | import ( 8 | "encoding/binary" 9 | "fmt" 10 | "io" 11 | "os" 12 | "strconv" 13 | "strings" 14 | ) 15 | 16 | const ( 17 | SAIAMAG = 0x8 18 | AIAFMAG = "`\n" 19 | AIAMAG = "\n" 20 | AIAMAGBIG = "\n" 21 | 22 | // Sizeof 23 | FL_HSZ_BIG = 0x80 24 | AR_HSZ_BIG = 0x70 25 | ) 26 | 27 | type bigarFileHeader struct { 28 | Flmagic [SAIAMAG]byte // Archive magic string 29 | Flmemoff [20]byte // Member table offset 30 | Flgstoff [20]byte // 32-bits global symtab offset 31 | Flgst64off [20]byte // 64-bits global symtab offset 32 | Flfstmoff [20]byte // First member offset 33 | Fllstmoff [20]byte // Last member offset 34 | Flfreeoff [20]byte // First member on free list offset 35 | } 36 | 37 | type bigarMemberHeader struct { 38 | Arsize [20]byte // File member size 39 | Arnxtmem [20]byte // Next member pointer 40 | Arprvmem [20]byte // Previous member pointer 41 | Ardate [12]byte // File member date 42 | Aruid [12]byte // File member uid 43 | Argid [12]byte // File member gid 44 | Armode [12]byte // File member mode (octal) 45 | Arnamlen [4]byte // File member name length 46 | // _ar_nam is removed because it's easier to get name without it. 47 | } 48 | 49 | // Archive represents an open AIX big archive. 50 | type Archive struct { 51 | ArchiveHeader 52 | Members []*Member 53 | 54 | closer io.Closer 55 | } 56 | 57 | // MemberHeader holds information about a big archive file header 58 | type ArchiveHeader struct { 59 | magic string 60 | } 61 | 62 | // Member represents a member of an AIX big archive. 63 | type Member struct { 64 | MemberHeader 65 | sr *io.SectionReader 66 | } 67 | 68 | // MemberHeader holds information about a big archive member 69 | type MemberHeader struct { 70 | Name string 71 | Size uint64 72 | } 73 | 74 | // OpenArchive opens the named archive using os.Open and prepares it for use 75 | // as an AIX big archive. 76 | func OpenArchive(name string) (*Archive, error) { 77 | f, err := os.Open(name) 78 | if err != nil { 79 | return nil, err 80 | } 81 | arch, err := NewArchive(f) 82 | if err != nil { 83 | f.Close() 84 | return nil, err 85 | } 86 | arch.closer = f 87 | return arch, nil 88 | } 89 | 90 | // Close closes the Archive. 91 | // If the Archive was created using NewArchive directly instead of OpenArchive, 92 | // Close has no effect. 93 | func (a *Archive) Close() error { 94 | var err error 95 | if a.closer != nil { 96 | err = a.closer.Close() 97 | a.closer = nil 98 | } 99 | return err 100 | } 101 | 102 | // NewArchive creates a new Archive for accessing an AIX big archive in an underlying reader. 103 | func NewArchive(r io.ReaderAt) (*Archive, error) { 104 | parseDecimalBytes := func(b []byte) (int64, error) { 105 | return strconv.ParseInt(strings.TrimSpace(string(b)), 10, 64) 106 | } 107 | sr := io.NewSectionReader(r, 0, 1<<63-1) 108 | 109 | // Read File Header 110 | var magic [SAIAMAG]byte 111 | if _, err := sr.ReadAt(magic[:], 0); err != nil { 112 | return nil, err 113 | } 114 | 115 | arch := new(Archive) 116 | switch string(magic[:]) { 117 | case AIAMAGBIG: 118 | arch.magic = string(magic[:]) 119 | case AIAMAG: 120 | return nil, fmt.Errorf("small AIX archive not supported") 121 | default: 122 | return nil, fmt.Errorf("unrecognised archive magic: 0x%x", magic) 123 | } 124 | 125 | var fhdr bigarFileHeader 126 | if _, err := sr.Seek(0, os.SEEK_SET); err != nil { 127 | return nil, err 128 | } 129 | if err := binary.Read(sr, binary.BigEndian, &fhdr); err != nil { 130 | return nil, err 131 | } 132 | 133 | off, err := parseDecimalBytes(fhdr.Flfstmoff[:]) 134 | if err != nil { 135 | return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) 136 | } 137 | 138 | if off == 0 { 139 | // Occurs if the archive is empty. 140 | return arch, nil 141 | } 142 | 143 | lastoff, err := parseDecimalBytes(fhdr.Fllstmoff[:]) 144 | if err != nil { 145 | return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) 146 | } 147 | 148 | // Read members 149 | for { 150 | // Read Member Header 151 | // The member header is normally 2 bytes larger. But it's easier 152 | // to read the name if the header is read without _ar_nam. 153 | // However, AIAFMAG must be read afterward. 154 | if _, err := sr.Seek(off, os.SEEK_SET); err != nil { 155 | return nil, err 156 | } 157 | 158 | var mhdr bigarMemberHeader 159 | if err := binary.Read(sr, binary.BigEndian, &mhdr); err != nil { 160 | return nil, err 161 | } 162 | 163 | member := new(Member) 164 | arch.Members = append(arch.Members, member) 165 | 166 | size, err := parseDecimalBytes(mhdr.Arsize[:]) 167 | if err != nil { 168 | return nil, fmt.Errorf("error parsing size in member header(%q); %v", mhdr, err) 169 | } 170 | member.Size = uint64(size) 171 | 172 | // Read name 173 | namlen, err := parseDecimalBytes(mhdr.Arnamlen[:]) 174 | if err != nil { 175 | return nil, fmt.Errorf("error parsing name length in member header(%q); %v", mhdr, err) 176 | } 177 | name := make([]byte, namlen) 178 | if err := binary.Read(sr, binary.BigEndian, name); err != nil { 179 | return nil, err 180 | } 181 | member.Name = string(name) 182 | 183 | fileoff := off + AR_HSZ_BIG + namlen 184 | if fileoff&1 != 0 { 185 | fileoff++ 186 | if _, err := sr.Seek(1, os.SEEK_CUR); err != nil { 187 | return nil, err 188 | } 189 | } 190 | 191 | // Read AIAFMAG string 192 | var fmag [2]byte 193 | if err := binary.Read(sr, binary.BigEndian, &fmag); err != nil { 194 | return nil, err 195 | } 196 | if string(fmag[:]) != AIAFMAG { 197 | return nil, fmt.Errorf("AIAFMAG not found after member header") 198 | } 199 | 200 | fileoff += 2 // Add the two bytes of AIAFMAG 201 | member.sr = io.NewSectionReader(sr, fileoff, size) 202 | 203 | if off == lastoff { 204 | break 205 | } 206 | off, err = parseDecimalBytes(mhdr.Arnxtmem[:]) 207 | if err != nil { 208 | return nil, fmt.Errorf("error parsing offset of first member in archive header(%q); %v", fhdr, err) 209 | } 210 | 211 | } 212 | 213 | return arch, nil 214 | 215 | } 216 | 217 | // GetFile returns the XCOFF file defined by member name. 218 | // FIXME: This doesn't work if an archive has two members with the same 219 | // name which can occur if a archive has both 32-bits and 64-bits files. 220 | func (arch *Archive) GetFile(name string) (*File, error) { 221 | for _, mem := range arch.Members { 222 | if mem.Name == name { 223 | return NewFile(mem.sr) 224 | } 225 | } 226 | return nil, fmt.Errorf("unknown member %s in archive", name) 227 | 228 | } 229 | -------------------------------------------------------------------------------- /utils/cat_goroutine.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "fmt" 6 | "github.com/pkg/errors" 7 | "runtime" 8 | "strconv" 9 | "sync" 10 | ) 11 | 12 | var goroutineSpace = []byte("goroutine ") 13 | 14 | var littleBuf = sync.Pool{ 15 | New: func() interface{} { 16 | buf := make([]byte, 64) 17 | return &buf 18 | }, 19 | } 20 | 21 | // parseUintBytes is like strconv.ParseUint, but using a []byte. 22 | func parseUintBytes(s []byte, base int, bitSize int) (n uint64, err error) { 23 | var cutoff, maxVal uint64 24 | 25 | if bitSize == 0 { 26 | bitSize = int(strconv.IntSize) 27 | } 28 | 29 | s0 := s 30 | switch { 31 | case len(s) < 1: 32 | err = strconv.ErrSyntax 33 | goto Error 34 | 35 | case 2 <= base && base <= 36: 36 | // valid base; nothing to do 37 | 38 | case base == 0: 39 | // Look for octal, hex prefix. 40 | switch { 41 | case s[0] == '0' && len(s) > 1 && (s[1] == 'x' || s[1] == 'X'): 42 | base = 16 43 | s = s[2:] 44 | if len(s) < 1 { 45 | err = strconv.ErrSyntax 46 | goto Error 47 | } 48 | case s[0] == '0': 49 | base = 8 50 | default: 51 | base = 10 52 | } 53 | 54 | default: 55 | err = errors.New("invalid base " + strconv.Itoa(base)) 56 | goto Error 57 | } 58 | 59 | n = 0 60 | cutoff = cutoff64(base) 61 | maxVal = 1<= base { 79 | n = 0 80 | err = strconv.ErrSyntax 81 | goto Error 82 | } 83 | 84 | if n >= cutoff { 85 | // n*base overflows 86 | n = 1<<64 - 1 87 | err = strconv.ErrRange 88 | goto Error 89 | } 90 | n *= uint64(base) 91 | 92 | n1 := n + uint64(v) 93 | if n1 < n || n1 > maxVal { 94 | // n+v overflows 95 | n = 1<<64 - 1 96 | err = strconv.ErrRange 97 | goto Error 98 | } 99 | n = n1 100 | } 101 | 102 | return n, nil 103 | 104 | Error: 105 | return n, &strconv.NumError{Func: "ParseUint", Num: string(s0), Err: err} 106 | } 107 | 108 | func CatGoroutineID() string { 109 | bp := littleBuf.Get().(*[]byte) 110 | defer littleBuf.Put(bp) 111 | b := *bp 112 | b = b[:runtime.Stack(b, false)] 113 | // Parse the 4707 out of "goroutine 4707 [" 114 | b = bytes.TrimPrefix(b, goroutineSpace) 115 | i := bytes.IndexByte(b, ' ') 116 | if i < 0 { 117 | panic(fmt.Sprintf("No space found in %q", b)) 118 | } 119 | b = b[:i] 120 | n, err := parseUintBytes(b, 10, 64) 121 | if err != nil { 122 | panic(fmt.Sprintf("Failed to parse goroutine ID out of %q: %v", b, err)) 123 | } 124 | return strconv.FormatUint(n, 10) 125 | } 126 | 127 | // Return the first number n such that n*base >= 1<<64. 128 | func cutoff64(base int) uint64 { 129 | if base < 2 { 130 | return 0 131 | } 132 | return (1<<64-1)/uint64(base) + 1 133 | } 134 | -------------------------------------------------------------------------------- /utils/fmt_stack.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bufio" 5 | "runtime" 6 | "strconv" 7 | "strings" 8 | ) 9 | 10 | const signatureLine = 6 11 | const callLine = 8 12 | const callFileLine = 9 13 | 14 | func FmtStack() (signature string, callerClass string, callerMethod string, callerLineNumber int) { 15 | l := 1 << 10 16 | buf := make([]byte, l) 17 | runtime.Stack(buf, false) 18 | s := byteToString(buf) 19 | r := strings.NewReader(s) 20 | reader := bufio.NewReader(r) 21 | n := 0 22 | for { 23 | l, e := reader.ReadString('\n') 24 | n++ 25 | if e != nil { 26 | break 27 | } 28 | if n == signatureLine { 29 | signature = l 30 | } 31 | if n == callLine { 32 | callArg := strings.Split(l, ".") 33 | callerClassArr := callArg[0 : len(callArg)-1] 34 | callerMethod = callArg[len(callArg)-1] 35 | callerClass = strings.Join(callerClassArr, ".") 36 | } 37 | if n == callFileLine { 38 | callFileLineBaseArr := strings.Split(l, " ") 39 | callFileLineArr := strings.Split(callFileLineBaseArr[0], ":") 40 | callerLineNumber, _ = strconv.Atoi(callFileLineArr[len(callFileLineArr)-1]) 41 | } 42 | if n > callFileLine { 43 | break 44 | } 45 | } 46 | return 47 | } 48 | -------------------------------------------------------------------------------- /utils/getIp.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "errors" 5 | "net" 6 | ) 7 | 8 | func ExternalIP() (net.IP, error) { 9 | ifaces, err := net.Interfaces() 10 | if err != nil { 11 | return nil, err 12 | } 13 | for _, iface := range ifaces { 14 | if iface.Flags&net.FlagUp == 0 { 15 | continue // interface down 16 | } 17 | if iface.Flags&net.FlagLoopback != 0 { 18 | continue // loopback interface 19 | } 20 | addrs, err := iface.Addrs() 21 | if err != nil { 22 | return nil, err 23 | } 24 | for _, addr := range addrs { 25 | ip := getIpFromAddr(addr) 26 | if ip == nil { 27 | continue 28 | } 29 | return ip, nil 30 | } 31 | } 32 | return nil, errors.New("connected to the network?") 33 | } 34 | 35 | func getIpFromAddr(addr net.Addr) net.IP { 36 | var ip net.IP 37 | switch v := addr.(type) { 38 | case *net.IPNet: 39 | ip = v.IP 40 | case *net.IPAddr: 41 | ip = v.IP 42 | } 43 | if ip == nil || ip.IsLoopback() { 44 | return nil 45 | } 46 | ip = ip.To4() 47 | if ip == nil { 48 | return nil // not an ipv4 address 49 | } 50 | 51 | return ip 52 | } 53 | -------------------------------------------------------------------------------- /utils/get_string_source.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "encoding/json" 5 | "reflect" 6 | "strconv" 7 | "unsafe" 8 | ) 9 | 10 | type stringStruct struct { 11 | str unsafe.Pointer 12 | len int 13 | } 14 | 15 | func Strval(value interface{}) string { 16 | // interface 转 string 17 | var key string 18 | if value == nil { 19 | return key 20 | } 21 | t := reflect.TypeOf(value) 22 | if t.Name() == "HTML" { 23 | return reflect.ValueOf(value).String() 24 | } 25 | switch value.(type) { 26 | case float64: 27 | ft := value.(float64) 28 | key = strconv.FormatFloat(ft, 'f', -1, 64) 29 | case float32: 30 | ft := value.(float32) 31 | key = strconv.FormatFloat(float64(ft), 'f', -1, 64) 32 | case int: 33 | it := value.(int) 34 | key = strconv.Itoa(it) 35 | case uint: 36 | it := value.(uint) 37 | key = strconv.Itoa(int(it)) 38 | case int8: 39 | it := value.(int8) 40 | key = strconv.Itoa(int(it)) 41 | case uint8: 42 | it := value.(uint8) 43 | key = strconv.Itoa(int(it)) 44 | case int16: 45 | it := value.(int16) 46 | key = strconv.Itoa(int(it)) 47 | case uint16: 48 | it := value.(uint16) 49 | key = strconv.Itoa(int(it)) 50 | case int32: 51 | it := value.(int32) 52 | key = strconv.Itoa(int(it)) 53 | case uint32: 54 | it := value.(uint32) 55 | key = strconv.Itoa(int(it)) 56 | case int64: 57 | it := value.(int64) 58 | key = strconv.FormatInt(it, 10) 59 | case uint64: 60 | it := value.(uint64) 61 | key = strconv.FormatUint(it, 10) 62 | case string: 63 | key = value.(string) 64 | case []byte: 65 | key = string(value.([]byte)) 66 | default: 67 | newValue, _ := json.Marshal(value) 68 | key = string(newValue) 69 | } 70 | return key 71 | } 72 | 73 | func GetSource(s interface{}) string { 74 | str := Strval(s) 75 | strPtr := uintptr((*(*stringStruct)(unsafe.Pointer(&str))).str) 76 | reStr := strconv.Itoa(int(strPtr)) 77 | return reStr 78 | } 79 | -------------------------------------------------------------------------------- /utils/gzip.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bytes" 5 | "compress/gzip" 6 | ) 7 | 8 | func GzipStr(str string) string { 9 | var b bytes.Buffer 10 | gz := gzip.NewWriter(&b) 11 | if _, err := gz.Write([]byte(str)); err != nil { 12 | panic(err) 13 | } 14 | if err := gz.Flush(); err != nil { 15 | panic(err) 16 | } 17 | if err := gz.Close(); err != nil { 18 | panic(err) 19 | } 20 | return b.String() 21 | } 22 | -------------------------------------------------------------------------------- /utils/is_hook.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "bufio" 5 | "runtime" 6 | "strings" 7 | "unsafe" 8 | ) 9 | 10 | func LoadFunc(skip int) string { 11 | pc, _, _, ok := runtime.Caller(skip) 12 | if ok { 13 | f := runtime.FuncForPC(pc) 14 | return f.Name() 15 | } 16 | return "" 17 | } 18 | 19 | func IsHook(string2 string, line int) (flag bool) { 20 | l := 1 << 10 21 | buf := make([]byte, l) 22 | runtime.Stack(buf, false) 23 | s := byteToString(buf) 24 | r := strings.NewReader(s) 25 | reader := bufio.NewReader(r) 26 | n := 0 27 | for { 28 | l, e := reader.ReadString('\n') 29 | n++ 30 | if n == line { 31 | if strings.Index(l, string2) > -1 { 32 | return true 33 | } 34 | } 35 | if e != nil { 36 | return flag 37 | } 38 | } 39 | } 40 | 41 | func byteToString(b []byte) string { 42 | return *(*string)(unsafe.Pointer(&b)) 43 | } 44 | -------------------------------------------------------------------------------- /utils/range_struct_filed.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "reflect" 5 | ) 6 | 7 | func RangeSource(i interface{}, needHook *[]interface{}) { 8 | t := reflect.TypeOf(i) 9 | v := reflect.ValueOf(i) 10 | if !v.IsValid() { 11 | return 12 | } 13 | if t.Kind() == reflect.Ptr { 14 | if v.IsNil() { 15 | return 16 | } 17 | t = t.Elem() 18 | v = v.Elem() 19 | in := v.Interface() 20 | RangeSource(in, needHook) 21 | return 22 | } 23 | if t.Kind() == reflect.Struct { 24 | RangeStructFiled(i, needHook) 25 | return 26 | } 27 | 28 | if t.Kind() == reflect.Slice { 29 | RangeStructSlice(i, needHook) 30 | return 31 | } 32 | 33 | if t.Kind() == reflect.Map { 34 | RangeStructMap(i, needHook) 35 | return 36 | } 37 | } 38 | 39 | func RangeStructFiled(i interface{}, needHook *[]interface{}) { 40 | t := reflect.TypeOf(i) 41 | var v reflect.Value 42 | var value reflect.Value 43 | v = reflect.ValueOf(i) 44 | fieldNum := t.NumField() 45 | for i := 0; i < fieldNum; i++ { 46 | if t.Field(i).PkgPath != "" { 47 | continue 48 | } 49 | k := t.Field(i).Name 50 | if v.Kind() == reflect.Struct { 51 | value = v.FieldByName(k) 52 | } 53 | if v.Kind() == reflect.Ptr { 54 | if v.IsNil() { 55 | continue 56 | } 57 | value = v.Elem().FieldByName(k) 58 | } 59 | if value.Kind() != reflect.Struct && value.Kind() != reflect.Ptr { 60 | if value.Kind() == reflect.String { 61 | *needHook = append(*needHook, value.Interface()) 62 | } 63 | } 64 | if value.Kind() == reflect.Struct || value.Kind() == reflect.Ptr || value.Kind() == reflect.Slice || value.Kind() == reflect.Map { 65 | if value.IsValid() { 66 | if value.Kind() == reflect.Ptr { 67 | continue 68 | } 69 | RangeSource(value.Interface(), needHook) 70 | } 71 | } 72 | } 73 | } 74 | 75 | func RangeStructSlice(i interface{}, needHook *[]interface{}) { 76 | v := reflect.ValueOf(i) 77 | for sl := 0; sl < v.Len(); sl++ { 78 | if v.Index(sl).Kind() == reflect.String { 79 | value := v.Index(sl) 80 | *needHook = append(*needHook, value.Interface()) 81 | } 82 | if v.Index(sl).Kind() == reflect.Interface { 83 | value := v.Index(sl) 84 | switch value.Interface().(type) { 85 | case string: 86 | *needHook = append(*needHook, value.Interface()) 87 | break 88 | default: 89 | RangeSource(value.Interface(), needHook) 90 | break 91 | } 92 | } 93 | 94 | if v.Index(sl).Kind() == reflect.Struct || v.Index(sl).Kind() == reflect.Ptr || v.Index(sl).Kind() == reflect.Slice || v.Index(sl).Kind() == reflect.Map { 95 | if v.Index(sl).Kind() == reflect.Ptr && v.Index(sl).IsNil() { 96 | continue 97 | } 98 | RangeSource(v.Index(sl).Interface(), needHook) 99 | } 100 | } 101 | } 102 | 103 | func RangeStructMap(i interface{}, needHook *[]interface{}) { 104 | v := reflect.ValueOf(i) 105 | for _, key := range v.MapKeys() { 106 | value := v.MapIndex(key) 107 | if key.Kind() == reflect.String { 108 | *needHook = append(*needHook, value.Interface()) 109 | } 110 | 111 | if value.Kind() == reflect.String { 112 | *needHook = append(*needHook, value.Interface()) 113 | } 114 | 115 | if key.Kind() == reflect.Struct || key.Kind() == reflect.Ptr || key.Kind() == reflect.Slice || key.Kind() == reflect.Map { 116 | if value.Kind() == reflect.Ptr && value.IsNil() { 117 | continue 118 | } 119 | RangeSource(key.Interface(), needHook) 120 | } 121 | 122 | if value.Kind() == reflect.Struct || value.Kind() == reflect.Ptr || value.Kind() == reflect.Slice || value.Kind() == reflect.Map { 123 | if value.Kind() == reflect.Ptr && value.IsNil() { 124 | continue 125 | } 126 | RangeSource(value.Interface(), needHook) 127 | } 128 | } 129 | } 130 | -------------------------------------------------------------------------------- /utils/server.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "github.com/shirou/gopsutil/cpu" 5 | "github.com/shirou/gopsutil/disk" 6 | "github.com/shirou/gopsutil/mem" 7 | "runtime" 8 | "time" 9 | ) 10 | 11 | const ( 12 | B = 1 13 | KB = 1024 * B 14 | MB = 1024 * KB 15 | GB = 1024 * MB 16 | ) 17 | 18 | type Server struct { 19 | Os Os `json:"os"` 20 | Cpu Cpu `json:"cpu"` 21 | Rrm Rrm `json:"ram"` 22 | Disk Disk `json:"disk"` 23 | } 24 | 25 | type Os struct { 26 | GOOS string `json:"goos"` 27 | NumCPU int `json:"numCpu"` 28 | Compiler string `json:"compiler"` 29 | GoVersion string `json:"goVersion"` 30 | NumGoroutine int `json:"numGoroutine"` 31 | } 32 | 33 | type Cpu struct { 34 | Cpus []float64 `json:"cpus"` 35 | Cores int `json:"cores"` 36 | } 37 | 38 | type Rrm struct { 39 | UsedMB int `json:"usedMb"` 40 | TotalMB int `json:"totalMb"` 41 | UsedPercent int `json:"usedPercent"` 42 | } 43 | 44 | type Disk struct { 45 | UsedMB int `json:"usedMb"` 46 | UsedGB int `json:"usedGb"` 47 | TotalMB int `json:"totalMb"` 48 | TotalGB int `json:"totalGb"` 49 | UsedPercent int `json:"usedPercent"` 50 | } 51 | 52 | func InitOS() (o Os) { 53 | o.GOOS = runtime.GOOS 54 | o.NumCPU = runtime.NumCPU() 55 | o.Compiler = runtime.Compiler 56 | o.GoVersion = runtime.Version() 57 | o.NumGoroutine = runtime.NumGoroutine() 58 | return o 59 | } 60 | 61 | func InitCPU() (c Cpu, err error) { 62 | if cores, err := cpu.Counts(false); err != nil { 63 | return c, err 64 | } else { 65 | c.Cores = cores 66 | } 67 | if cpus, err := cpu.Percent(time.Duration(200)*time.Millisecond, true); err != nil { 68 | return c, err 69 | } else { 70 | c.Cpus = cpus 71 | } 72 | return c, nil 73 | } 74 | 75 | func InitRAM() (r Rrm, err error) { 76 | if u, err := mem.VirtualMemory(); err != nil { 77 | return r, err 78 | } else { 79 | r.UsedMB = int(u.Used) / MB 80 | r.TotalMB = int(u.Total) / MB 81 | r.UsedPercent = int(u.UsedPercent) 82 | } 83 | return r, nil 84 | } 85 | 86 | func InitDisk() (d Disk, err error) { 87 | if u, err := disk.Usage("/"); err != nil { 88 | return d, err 89 | } else { 90 | d.UsedMB = int(u.Used) / MB 91 | d.UsedGB = int(u.Used) / GB 92 | d.TotalMB = int(u.Total) / MB 93 | d.TotalGB = int(u.Total) / GB 94 | d.UsedPercent = int(u.UsedPercent) 95 | } 96 | return d, nil 97 | } 98 | -------------------------------------------------------------------------------- /utils/sha1.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "crypto/sha1" 5 | "encoding/hex" 6 | ) 7 | 8 | func SHA1(s string) string { 9 | o := sha1.New() 10 | o.Write([]byte(s)) 11 | return hex.EncodeToString(o.Sum(nil)) 12 | } 13 | -------------------------------------------------------------------------------- /utils/snowFlake.go: -------------------------------------------------------------------------------- 1 | package utils 2 | 3 | import ( 4 | "fmt" 5 | "sync" 6 | "time" 7 | ) 8 | 9 | //你需要先去了解下 golang中 & | << >> 几个符号产生的运算意义 10 | const ( 11 | workerBits uint8 = 10 //10bit工作机器的id,如果你发现1024台机器不够那就调大次值 12 | numberBits uint8 = 12 //12bit 工作序号,如果你发现1毫秒并发生成4096个唯一id不够请调大次值 13 | workerMax int64 = -1 ^ (-1 << workerBits) 14 | numberMax int64 = -1 ^ (-1 << numberBits) 15 | timeShift uint8 = workerBits + numberBits 16 | workerShift uint8 = numberBits 17 | // 如果在程序跑了一段时间修改了epoch这个值 可能会导致生成相同的ID, 18 | //这个值请自行设置为你系统准备上线前的精确到毫秒级别的时间戳,因为雪花时间戳保证唯一的部分最多管69年(2的41次方), 19 | //所以此值设置为你当前时间戳能够保证你的系统是从当前时间开始往后推69年 20 | startTime int64 = 1525705533000 21 | ) 22 | 23 | type Worker struct { 24 | mu sync.Mutex 25 | timestamp int64 26 | workerId int64 27 | number int64 28 | agentId int 29 | } 30 | 31 | func NewWorker(AgentId int) (*Worker, error) { 32 | // 生成一个新节点 33 | return &Worker{ 34 | timestamp: 0, 35 | workerId: 1, 36 | number: 0, 37 | agentId: AgentId, 38 | }, nil 39 | } 40 | 41 | func (w *Worker) GetId() int64 { 42 | w.mu.Lock() 43 | defer w.mu.Unlock() 44 | now := time.Now().UnixNano() / 1e6 45 | if w.timestamp == now { 46 | w.number++ 47 | if w.number > numberMax { 48 | for now <= w.timestamp { 49 | now = time.Now().UnixNano() / 1e6 50 | } 51 | } 52 | } else { 53 | w.number = 0 54 | w.timestamp = now 55 | } 56 | //以下表达式才是主菜 57 | // (now-startTime)<