├── .github └── workflows │ └── rust.yml ├── .gitignore ├── Cargo.toml ├── LICENSE ├── README.md ├── configure ├── docs ├── example.md ├── faq.md ├── images │ ├── banner.jpg │ ├── fs.png │ ├── graph.png │ ├── ps.png │ ├── v4.png │ └── v6.png └── install.md ├── probes ├── execsnoop.c └── tcpconnect.c ├── scripts └── build_script.py └── src ├── cli ├── check.rs └── mod.rs ├── ebpf ├── execsnoop.rs ├── mod.rs ├── opensnoop.rs ├── tcpconnect.rs ├── types.rs └── utils.rs ├── main.rs ├── server.rs ├── storage ├── log.rs ├── mod.rs ├── types.rs └── utils.rs └── visualization ├── connect.rs ├── exec.rs ├── mod.rs ├── open.rs └── utils.rs /.github/workflows/rust.yml: -------------------------------------------------------------------------------- 1 | name: Rust 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | env: 10 | CARGO_TERM_COLOR: always 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | 17 | steps: 18 | - uses: actions/checkout@v2 19 | - name: Install latest nightly 20 | uses: actions-rs/toolchain@v1 21 | with: 22 | toolchain: nightly 23 | override: true 24 | components: rustfmt, clippy 25 | - name: Install bcc 26 | run: | 27 | sudo apt-get install bpfcc-tools linux-headers-$(uname -r) 28 | sudo ln -s /usr/lib/x86_64-linux-gnu/libbcc.so.0 /usr/lib/x86_64-linux-gnu/libbcc.so 29 | - name: Build 30 | run: | 31 | ./configure 32 | cargo build --verbose 33 | - name: Run tests 34 | run: cargo test --verbose -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vscode 2 | /target 3 | Cargo.lock 4 | probes/opensnoop.c 5 | build.rs -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "foxear" 3 | version = "0.1.1" 4 | edition = "2021" 5 | license = "MPL-2.0" 6 | authors = ["LI Rui "] 7 | readme = "README.md" 8 | description = "Fox Ear is a Linux process behavior trace tool powered by eBPF." 9 | repository = "https://github.com/KernelErr/foxear" 10 | keywords = ["ebpf", "tracing", "debug", "linux"] 11 | categories = ["development-tools"] 12 | 13 | include = ["/src", "/probes", "build.rs"] 14 | 15 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 16 | 17 | [dependencies] 18 | # eBPF related 19 | bcc = "0.0.32" 20 | libc = "0.2" 21 | 22 | # Analyse related 23 | 24 | # Storage related 25 | csv = "1.1" 26 | serde = { version = "1.0", features = ["derive"] } 27 | sled = "0.34" 28 | chrono = "0.4" 29 | nanoid = "0.4" 30 | 31 | # Config related 32 | config = { version = "0.11", features = ["toml"] } 33 | 34 | # Visualization related 35 | petgraph = "0.6.0" 36 | cli-table = { version = "0.4", features = ["csv"] } 37 | 38 | # Cli related 39 | clap = { version = "3.0.0", features = ["cargo"] } 40 | 41 | anyhow = "1.0" 42 | futures = "0.3" 43 | tokio = { version = "1.15.0", features = ["full"] } 44 | lockfree = "0.5" 45 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Mozilla Public License Version 2.0 2 | ================================== 3 | 4 | 1. Definitions 5 | -------------- 6 | 7 | 1.1. "Contributor" 8 | means each individual or legal entity that creates, contributes to 9 | the creation of, or owns Covered Software. 10 | 11 | 1.2. "Contributor Version" 12 | means the combination of the Contributions of others (if any) used 13 | by a Contributor and that particular Contributor's Contribution. 14 | 15 | 1.3. "Contribution" 16 | means Covered Software of a particular Contributor. 17 | 18 | 1.4. "Covered Software" 19 | means Source Code Form to which the initial Contributor has attached 20 | the notice in Exhibit A, the Executable Form of such Source Code 21 | Form, and Modifications of such Source Code Form, in each case 22 | including portions thereof. 23 | 24 | 1.5. "Incompatible With Secondary Licenses" 25 | means 26 | 27 | (a) that the initial Contributor has attached the notice described 28 | in Exhibit B to the Covered Software; or 29 | 30 | (b) that the Covered Software was made available under the terms of 31 | version 1.1 or earlier of the License, but not also under the 32 | terms of a Secondary License. 33 | 34 | 1.6. "Executable Form" 35 | means any form of the work other than Source Code Form. 36 | 37 | 1.7. "Larger Work" 38 | means a work that combines Covered Software with other material, in 39 | a separate file or files, that is not Covered Software. 40 | 41 | 1.8. "License" 42 | means this document. 43 | 44 | 1.9. "Licensable" 45 | means having the right to grant, to the maximum extent possible, 46 | whether at the time of the initial grant or subsequently, any and 47 | all of the rights conveyed by this License. 48 | 49 | 1.10. "Modifications" 50 | means any of the following: 51 | 52 | (a) any file in Source Code Form that results from an addition to, 53 | deletion from, or modification of the contents of Covered 54 | Software; or 55 | 56 | (b) any new file in Source Code Form that contains any Covered 57 | Software. 58 | 59 | 1.11. "Patent Claims" of a Contributor 60 | means any patent claim(s), including without limitation, method, 61 | process, and apparatus claims, in any patent Licensable by such 62 | Contributor that would be infringed, but for the grant of the 63 | License, by the making, using, selling, offering for sale, having 64 | made, import, or transfer of either its Contributions or its 65 | Contributor Version. 66 | 67 | 1.12. "Secondary License" 68 | means either the GNU General Public License, Version 2.0, the GNU 69 | Lesser General Public License, Version 2.1, the GNU Affero General 70 | Public License, Version 3.0, or any later versions of those 71 | licenses. 72 | 73 | 1.13. "Source Code Form" 74 | means the form of the work preferred for making modifications. 75 | 76 | 1.14. "You" (or "Your") 77 | means an individual or a legal entity exercising rights under this 78 | License. For legal entities, "You" includes any entity that 79 | controls, is controlled by, or is under common control with You. For 80 | purposes of this definition, "control" means (a) the power, direct 81 | or indirect, to cause the direction or management of such entity, 82 | whether by contract or otherwise, or (b) ownership of more than 83 | fifty percent (50%) of the outstanding shares or beneficial 84 | ownership of such entity. 85 | 86 | 2. License Grants and Conditions 87 | -------------------------------- 88 | 89 | 2.1. Grants 90 | 91 | Each Contributor hereby grants You a world-wide, royalty-free, 92 | non-exclusive license: 93 | 94 | (a) under intellectual property rights (other than patent or trademark) 95 | Licensable by such Contributor to use, reproduce, make available, 96 | modify, display, perform, distribute, and otherwise exploit its 97 | Contributions, either on an unmodified basis, with Modifications, or 98 | as part of a Larger Work; and 99 | 100 | (b) under Patent Claims of such Contributor to make, use, sell, offer 101 | for sale, have made, import, and otherwise transfer either its 102 | Contributions or its Contributor Version. 103 | 104 | 2.2. Effective Date 105 | 106 | The licenses granted in Section 2.1 with respect to any Contribution 107 | become effective for each Contribution on the date the Contributor first 108 | distributes such Contribution. 109 | 110 | 2.3. Limitations on Grant Scope 111 | 112 | The licenses granted in this Section 2 are the only rights granted under 113 | this License. No additional rights or licenses will be implied from the 114 | distribution or licensing of Covered Software under this License. 115 | Notwithstanding Section 2.1(b) above, no patent license is granted by a 116 | Contributor: 117 | 118 | (a) for any code that a Contributor has removed from Covered Software; 119 | or 120 | 121 | (b) for infringements caused by: (i) Your and any other third party's 122 | modifications of Covered Software, or (ii) the combination of its 123 | Contributions with other software (except as part of its Contributor 124 | Version); or 125 | 126 | (c) under Patent Claims infringed by Covered Software in the absence of 127 | its Contributions. 128 | 129 | This License does not grant any rights in the trademarks, service marks, 130 | or logos of any Contributor (except as may be necessary to comply with 131 | the notice requirements in Section 3.4). 132 | 133 | 2.4. Subsequent Licenses 134 | 135 | No Contributor makes additional grants as a result of Your choice to 136 | distribute the Covered Software under a subsequent version of this 137 | License (see Section 10.2) or under the terms of a Secondary License (if 138 | permitted under the terms of Section 3.3). 139 | 140 | 2.5. Representation 141 | 142 | Each Contributor represents that the Contributor believes its 143 | Contributions are its original creation(s) or it has sufficient rights 144 | to grant the rights to its Contributions conveyed by this License. 145 | 146 | 2.6. Fair Use 147 | 148 | This License is not intended to limit any rights You have under 149 | applicable copyright doctrines of fair use, fair dealing, or other 150 | equivalents. 151 | 152 | 2.7. Conditions 153 | 154 | Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted 155 | in Section 2.1. 156 | 157 | 3. Responsibilities 158 | ------------------- 159 | 160 | 3.1. Distribution of Source Form 161 | 162 | All distribution of Covered Software in Source Code Form, including any 163 | Modifications that You create or to which You contribute, must be under 164 | the terms of this License. You must inform recipients that the Source 165 | Code Form of the Covered Software is governed by the terms of this 166 | License, and how they can obtain a copy of this License. You may not 167 | attempt to alter or restrict the recipients' rights in the Source Code 168 | Form. 169 | 170 | 3.2. Distribution of Executable Form 171 | 172 | If You distribute Covered Software in Executable Form then: 173 | 174 | (a) such Covered Software must also be made available in Source Code 175 | Form, as described in Section 3.1, and You must inform recipients of 176 | the Executable Form how they can obtain a copy of such Source Code 177 | Form by reasonable means in a timely manner, at a charge no more 178 | than the cost of distribution to the recipient; and 179 | 180 | (b) You may distribute such Executable Form under the terms of this 181 | License, or sublicense it under different terms, provided that the 182 | license for the Executable Form does not attempt to limit or alter 183 | the recipients' rights in the Source Code Form under this License. 184 | 185 | 3.3. Distribution of a Larger Work 186 | 187 | You may create and distribute a Larger Work under terms of Your choice, 188 | provided that You also comply with the requirements of this License for 189 | the Covered Software. If the Larger Work is a combination of Covered 190 | Software with a work governed by one or more Secondary Licenses, and the 191 | Covered Software is not Incompatible With Secondary Licenses, this 192 | License permits You to additionally distribute such Covered Software 193 | under the terms of such Secondary License(s), so that the recipient of 194 | the Larger Work may, at their option, further distribute the Covered 195 | Software under the terms of either this License or such Secondary 196 | License(s). 197 | 198 | 3.4. Notices 199 | 200 | You may not remove or alter the substance of any license notices 201 | (including copyright notices, patent notices, disclaimers of warranty, 202 | or limitations of liability) contained within the Source Code Form of 203 | the Covered Software, except that You may alter any license notices to 204 | the extent required to remedy known factual inaccuracies. 205 | 206 | 3.5. Application of Additional Terms 207 | 208 | You may choose to offer, and to charge a fee for, warranty, support, 209 | indemnity or liability obligations to one or more recipients of Covered 210 | Software. However, You may do so only on Your own behalf, and not on 211 | behalf of any Contributor. You must make it absolutely clear that any 212 | such warranty, support, indemnity, or liability obligation is offered by 213 | You alone, and You hereby agree to indemnify every Contributor for any 214 | liability incurred by such Contributor as a result of warranty, support, 215 | indemnity or liability terms You offer. You may include additional 216 | disclaimers of warranty and limitations of liability specific to any 217 | jurisdiction. 218 | 219 | 4. Inability to Comply Due to Statute or Regulation 220 | --------------------------------------------------- 221 | 222 | If it is impossible for You to comply with any of the terms of this 223 | License with respect to some or all of the Covered Software due to 224 | statute, judicial order, or regulation then You must: (a) comply with 225 | the terms of this License to the maximum extent possible; and (b) 226 | describe the limitations and the code they affect. Such description must 227 | be placed in a text file included with all distributions of the Covered 228 | Software under this License. Except to the extent prohibited by statute 229 | or regulation, such description must be sufficiently detailed for a 230 | recipient of ordinary skill to be able to understand it. 231 | 232 | 5. Termination 233 | -------------- 234 | 235 | 5.1. The rights granted under this License will terminate automatically 236 | if You fail to comply with any of its terms. However, if You become 237 | compliant, then the rights granted under this License from a particular 238 | Contributor are reinstated (a) provisionally, unless and until such 239 | Contributor explicitly and finally terminates Your grants, and (b) on an 240 | ongoing basis, if such Contributor fails to notify You of the 241 | non-compliance by some reasonable means prior to 60 days after You have 242 | come back into compliance. Moreover, Your grants from a particular 243 | Contributor are reinstated on an ongoing basis if such Contributor 244 | notifies You of the non-compliance by some reasonable means, this is the 245 | first time You have received notice of non-compliance with this License 246 | from such Contributor, and You become compliant prior to 30 days after 247 | Your receipt of the notice. 248 | 249 | 5.2. If You initiate litigation against any entity by asserting a patent 250 | infringement claim (excluding declaratory judgment actions, 251 | counter-claims, and cross-claims) alleging that a Contributor Version 252 | directly or indirectly infringes any patent, then the rights granted to 253 | You by any and all Contributors for the Covered Software under Section 254 | 2.1 of this License shall terminate. 255 | 256 | 5.3. In the event of termination under Sections 5.1 or 5.2 above, all 257 | end user license agreements (excluding distributors and resellers) which 258 | have been validly granted by You or Your distributors under this License 259 | prior to termination shall survive termination. 260 | 261 | ************************************************************************ 262 | * * 263 | * 6. Disclaimer of Warranty * 264 | * ------------------------- * 265 | * * 266 | * Covered Software is provided under this License on an "as is" * 267 | * basis, without warranty of any kind, either expressed, implied, or * 268 | * statutory, including, without limitation, warranties that the * 269 | * Covered Software is free of defects, merchantable, fit for a * 270 | * particular purpose or non-infringing. The entire risk as to the * 271 | * quality and performance of the Covered Software is with You. * 272 | * Should any Covered Software prove defective in any respect, You * 273 | * (not any Contributor) assume the cost of any necessary servicing, * 274 | * repair, or correction. This disclaimer of warranty constitutes an * 275 | * essential part of this License. No use of any Covered Software is * 276 | * authorized under this License except under this disclaimer. * 277 | * * 278 | ************************************************************************ 279 | 280 | ************************************************************************ 281 | * * 282 | * 7. Limitation of Liability * 283 | * -------------------------- * 284 | * * 285 | * Under no circumstances and under no legal theory, whether tort * 286 | * (including negligence), contract, or otherwise, shall any * 287 | * Contributor, or anyone who distributes Covered Software as * 288 | * permitted above, be liable to You for any direct, indirect, * 289 | * special, incidental, or consequential damages of any character * 290 | * including, without limitation, damages for lost profits, loss of * 291 | * goodwill, work stoppage, computer failure or malfunction, or any * 292 | * and all other commercial damages or losses, even if such party * 293 | * shall have been informed of the possibility of such damages. This * 294 | * limitation of liability shall not apply to liability for death or * 295 | * personal injury resulting from such party's negligence to the * 296 | * extent applicable law prohibits such limitation. Some * 297 | * jurisdictions do not allow the exclusion or limitation of * 298 | * incidental or consequential damages, so this exclusion and * 299 | * limitation may not apply to You. * 300 | * * 301 | ************************************************************************ 302 | 303 | 8. Litigation 304 | ------------- 305 | 306 | Any litigation relating to this License may be brought only in the 307 | courts of a jurisdiction where the defendant maintains its principal 308 | place of business and such litigation shall be governed by laws of that 309 | jurisdiction, without reference to its conflict-of-law provisions. 310 | Nothing in this Section shall prevent a party's ability to bring 311 | cross-claims or counter-claims. 312 | 313 | 9. Miscellaneous 314 | ---------------- 315 | 316 | This License represents the complete agreement concerning the subject 317 | matter hereof. If any provision of this License is held to be 318 | unenforceable, such provision shall be reformed only to the extent 319 | necessary to make it enforceable. Any law or regulation which provides 320 | that the language of a contract shall be construed against the drafter 321 | shall not be used to construe this License against a Contributor. 322 | 323 | 10. Versions of the License 324 | --------------------------- 325 | 326 | 10.1. New Versions 327 | 328 | Mozilla Foundation is the license steward. Except as provided in Section 329 | 10.3, no one other than the license steward has the right to modify or 330 | publish new versions of this License. Each version will be given a 331 | distinguishing version number. 332 | 333 | 10.2. Effect of New Versions 334 | 335 | You may distribute the Covered Software under the terms of the version 336 | of the License under which You originally received the Covered Software, 337 | or under the terms of any subsequent version published by the license 338 | steward. 339 | 340 | 10.3. Modified Versions 341 | 342 | If you create software not governed by this License, and you want to 343 | create a new license for such software, you may create and use a 344 | modified version of this License if you rename the license and remove 345 | any references to the name of the license steward (except to note that 346 | such modified license differs from this License). 347 | 348 | 10.4. Distributing Source Code Form that is Incompatible With Secondary 349 | Licenses 350 | 351 | If You choose to distribute Source Code Form that is Incompatible With 352 | Secondary Licenses under the terms of this version of the License, the 353 | notice described in Exhibit B of this License must be attached. 354 | 355 | Exhibit A - Source Code Form License Notice 356 | ------------------------------------------- 357 | 358 | This Source Code Form is subject to the terms of the Mozilla Public 359 | License, v. 2.0. If a copy of the MPL was not distributed with this 360 | file, You can obtain one at http://mozilla.org/MPL/2.0/. 361 | 362 | If it is not possible or desirable to put the notice in a particular 363 | file, then You may include the notice in a location (such as a LICENSE 364 | file in a relevant directory) where a recipient would be likely to look 365 | for such a notice. 366 | 367 | You may add additional accurate notices of copyright ownership. 368 | 369 | Exhibit B - "Incompatible With Secondary Licenses" Notice 370 | --------------------------------------------------------- 371 | 372 | This Source Code Form is "Incompatible With Secondary Licenses", as 373 | defined by the Mozilla Public License, v. 2.0. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![Banner](./docs/images/banner.jpg) 2 | 3 | # Fox Ear 4 | 5 | Fox Ear is a Linux process behavior trace tool powered by eBPF. 6 | 7 | Banner image by [Birger Strahl](https://unsplash.com/@bist31?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText) on [Unsplash](https://unsplash.com/s/photos/fox?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText). 8 | 9 | ## Features 10 | 11 | - Log process and its subprocesses' creation and create a graph. 12 | - Log processes' file access. 13 | - Log processes' TCP connection(IPv4 and IPv6). 14 | 15 | ## Documents 16 | 17 | - [Install](./docs/install.md) 18 | - [Example](./docs/example.md) 19 | - [FAQ](./docs/faq.md) 20 | 21 | ## License 22 | 23 | Fox Ear is available under the **MPL-2.0** license. You can read an [explanation](https://tldrlegal.com/license/mozilla-public-license-2.0-(mpl-2)) about it, but only the full text of MPL-2.0 has legal effect. 24 | 25 | Fox Ear used some parts of following projects: 26 | 27 | - Probes - [bcc](https://github.com/iovisor/bcc) (Apache-2.0) -------------------------------------------------------------------------------- /configure: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | sudo python3 scripts/build_script.py 4 | sudo chown "${USER}":"${USER}" build.rs -------------------------------------------------------------------------------- /docs/example.md: -------------------------------------------------------------------------------- 1 | # Example 2 | 3 | This example will show you how to use Fox Ear to trace Linux process. Notice Fox Ear store logs in `csv` format, it's easy to load log into other scripts or programs. 4 | 5 | First, we opened two terminals, one for Fox Ear, one for our custom command. In the second terminal, we use `echo $$` to get current PID. 6 | 7 | ```shell 8 | 2$ echo $$ 9 | 106313 10 | ``` 11 | 12 | Now we use Fox Ear to watch this process. As we will load eBPF module into the kernel, we need **root** permission. 13 | 14 | ```shell 15 | 1# foxear watch 106313 16 | Watching PID 106313 17 | Waiting for building eBPF... 18 | Logs are stored at /var/lib/foxear/logs/3 19 | eBPF is ready 20 | ``` 21 | 22 | When `eBPF is ready`, you can use the previous terminal to execute any process that you want. 23 | 24 | ```shell 25 | 2$ whoami 26 | 2$ curl http://127.0.0.1 27 | 2$ sudo su 28 | 2# whoami 29 | 2# curl http://127.0.0.1 30 | 2# curl http://[::1] 31 | 2# cat /etc/hosts 32 | 2# exit 33 | ``` 34 | 35 | When all done, you can close this terminal and send `Ctrl-C` to Fox Ear. 36 | 37 | ## Show process list 38 | 39 | As logs are stored at `/var/lib/foxear/logs/3` in the output above, the ID of this task is 3. 40 | 41 | ```shell 42 | 1# foxear check 3 ps 43 | ``` 44 | 45 | ![ps](./images/ps.png) 46 | 47 | ## Show process graph 48 | 49 | To get the graph showed, you may need tools like [xdot](https://github.com/jrfonseca/xdot.py). 50 | 51 | ```shell 52 | 1# foxear check 3 graph 53 | 3$ xdot /var/lib/foxear/logs/3/reports/exec.dot 54 | ``` 55 | 56 | ![graph](./images/graph.png) 57 | 58 | ## Show file access 59 | 60 | ```shell 61 | 1# foxear check 3 fs 62 | ``` 63 | 64 | ![ps](./images/fs.png) 65 | 66 | ## Show IPv4 TCP connections 67 | 68 | ```shell 69 | 1# foxear check 3 v4 70 | ``` 71 | 72 | ![ps](./images/v4.png) 73 | 74 | ## Show IPv6 TCP connections 75 | 76 | ```shell 77 | 1# foxear check 3 v6 78 | ``` 79 | 80 | ![ps](./images/v6.png) -------------------------------------------------------------------------------- /docs/faq.md: -------------------------------------------------------------------------------- 1 | ## FAQ 2 | 3 | ## Can not find `-lbcc` 4 | 5 | 1. Install [bcc](https://github.com/iovisor/bcc) first. 6 | 2. Make a symbol link for `libbcc.so` like: `sudo ln -s /usr/lib/x86_64-linux-gnu/libbcc.so.0 /usr/lib/x86_64-linux-gnu/libbcc.so`. -------------------------------------------------------------------------------- /docs/images/banner.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/banner.jpg -------------------------------------------------------------------------------- /docs/images/fs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/fs.png -------------------------------------------------------------------------------- /docs/images/graph.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/graph.png -------------------------------------------------------------------------------- /docs/images/ps.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/ps.png -------------------------------------------------------------------------------- /docs/images/v4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/v4.png -------------------------------------------------------------------------------- /docs/images/v6.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/KernelErr/foxear/1ffd8e3726d1d7df9ece828e1317ec5eae547b9d/docs/images/v6.png -------------------------------------------------------------------------------- /docs/install.md: -------------------------------------------------------------------------------- 1 | # Installation 2 | 3 | Fox Ear is written in Rust, C and Python. And the minimal supported version of Linux kernel is 5.6 as eBPF features' requirements. As kernels for different Linux flavors may varies, it's recommended to compile Fox Ear on your computer rather than using a prebuilt binary. 4 | 5 | ## Requirements 6 | 7 | - Linux kernel >= 5.6 8 | - [bcc](https://github.com/iovisor/bcc) toolchain - [bcc/INSTALL.md](https://github.com/iovisor/bcc/blob/master/INSTALL.md) 9 | - Linux header 10 | - Rust toolchain 11 | - Python 3 12 | 13 | ## Compile 14 | 15 | First, you should use `./configure` to generate configure fitting your kernel. 16 | 17 | ``` 18 | $ ./configure 19 | ``` 20 | 21 | Then use `cargo` to compile. 22 | 23 | ``` 24 | $ cargo build --release 25 | ``` 26 | 27 | Or you can use `cargo install --path .` to install Fox Ear and add it into your path. 28 | 29 | ## Usage 30 | 31 | Check [Example](./example.md). 32 | -------------------------------------------------------------------------------- /probes/execsnoop.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #define ARGSIZE 128 5 | enum event_type { 6 | EVENT_ARG, 7 | EVENT_RET, 8 | }; 9 | struct data_t { 10 | u32 pid; // PID as in the userspace term (i.e. task->tgid in kernel) 11 | u32 ppid; // Parent PID as in the userspace term (i.e task->real_parent->tgid in kernel) 12 | u32 uid; 13 | char comm[TASK_COMM_LEN]; 14 | enum event_type type; 15 | char argv[ARGSIZE]; 16 | int retval; 17 | }; 18 | BPF_PERF_OUTPUT(events); 19 | static int __submit_arg(struct pt_regs *ctx, void *ptr, struct data_t *data) 20 | { 21 | bpf_probe_read_user(data->argv, sizeof(data->argv), ptr); 22 | events.perf_submit(ctx, data, sizeof(struct data_t)); 23 | return 1; 24 | } 25 | static int submit_arg(struct pt_regs *ctx, void *ptr, struct data_t *data) 26 | { 27 | const char *argp = NULL; 28 | bpf_probe_read_user(&argp, sizeof(argp), ptr); 29 | if (argp) { 30 | return __submit_arg(ctx, (void *)(argp), data); 31 | } 32 | return 0; 33 | } 34 | int syscall__execve(struct pt_regs *ctx, 35 | const char __user *filename, 36 | const char __user *const __user *__argv, 37 | const char __user *const __user *__envp) 38 | { 39 | u32 uid = bpf_get_current_uid_gid() & 0xffffffff; 40 | // create data here and pass to submit_arg to save stack space (#555) 41 | struct data_t data = {}; 42 | struct task_struct *task; 43 | data.pid = bpf_get_current_pid_tgid() >> 32; 44 | task = (struct task_struct *)bpf_get_current_task(); 45 | // Some kernels, like Ubuntu 4.13.0-generic, return 0 46 | // as the real_parent->tgid. 47 | // We use the get_ppid function as a fallback in those cases. (#1883) 48 | data.ppid = task->real_parent->tgid; 49 | bpf_get_current_comm(&data.comm, sizeof(data.comm)); 50 | data.type = EVENT_ARG; 51 | __submit_arg(ctx, (void *)filename, &data); 52 | // skip first arg, as we submitted filename 53 | #pragma unroll 54 | for (int i = 1; i < 20; i++) { 55 | if (submit_arg(ctx, (void *)&__argv[i], &data) == 0) 56 | goto out; 57 | } 58 | // handle truncated argument list 59 | char ellipsis[] = "..."; 60 | __submit_arg(ctx, (void *)ellipsis, &data); 61 | out: 62 | return 0; 63 | } 64 | int do_ret_sys_execve(struct pt_regs *ctx) 65 | { 66 | struct data_t data = {}; 67 | struct task_struct *task; 68 | u32 uid = bpf_get_current_uid_gid() & 0xffffffff; 69 | data.pid = bpf_get_current_pid_tgid() >> 32; 70 | data.uid = uid; 71 | task = (struct task_struct *)bpf_get_current_task(); 72 | // Some kernels, like Ubuntu 4.13.0-generic, return 0 73 | // as the real_parent->tgid. 74 | // We use the get_ppid function as a fallback in those cases. (#1883) 75 | data.ppid = task->real_parent->tgid; 76 | bpf_get_current_comm(&data.comm, sizeof(data.comm)); 77 | data.type = EVENT_RET; 78 | data.retval = PT_REGS_RC(ctx); 79 | events.perf_submit(ctx, &data, sizeof(data)); 80 | return 0; 81 | } -------------------------------------------------------------------------------- /probes/tcpconnect.c: -------------------------------------------------------------------------------- 1 | static inline int _cgroup_filter() 2 | { 3 | return 0; 4 | } 5 | 6 | static inline int _mntns_filter() 7 | { 8 | return 0; 9 | } 10 | 11 | static inline int container_should_be_filtered() 12 | { 13 | return _cgroup_filter() || _mntns_filter(); 14 | } 15 | 16 | #include 17 | #include 18 | #include 19 | 20 | BPF_HASH(currsock, u32, struct sock *); 21 | 22 | // separate data structs for ipv4 and ipv6 23 | struct ipv4_data_t 24 | { 25 | u64 ts_us; 26 | u32 pid; 27 | u32 uid; 28 | u32 saddr; 29 | u32 daddr; 30 | u64 ip; 31 | u16 lport; 32 | u16 dport; 33 | char task[TASK_COMM_LEN]; 34 | }; 35 | BPF_PERF_OUTPUT(ipv4_events); 36 | 37 | struct ipv6_data_t 38 | { 39 | u64 ts_us; 40 | u32 pid; 41 | u32 uid; 42 | unsigned __int128 saddr; 43 | unsigned __int128 daddr; 44 | u64 ip; 45 | u16 lport; 46 | u16 dport; 47 | char task[TASK_COMM_LEN]; 48 | }; 49 | BPF_PERF_OUTPUT(ipv6_events); 50 | 51 | // separate flow keys per address family 52 | struct ipv4_flow_key_t 53 | { 54 | u32 saddr; 55 | u32 daddr; 56 | u16 dport; 57 | }; 58 | BPF_HASH(ipv4_count, struct ipv4_flow_key_t); 59 | 60 | struct ipv6_flow_key_t 61 | { 62 | unsigned __int128 saddr; 63 | unsigned __int128 daddr; 64 | u16 dport; 65 | }; 66 | BPF_HASH(ipv6_count, struct ipv6_flow_key_t); 67 | 68 | int trace_connect_entry(struct pt_regs *ctx, struct sock *sk) 69 | { 70 | if (container_should_be_filtered()) 71 | { 72 | return 0; 73 | } 74 | 75 | u64 pid_tgid = bpf_get_current_pid_tgid(); 76 | u32 pid = pid_tgid >> 32; 77 | u32 tid = pid_tgid; 78 | 79 | u32 uid = bpf_get_current_uid_gid(); 80 | 81 | // stash the sock ptr for lookup on return 82 | currsock.update(&tid, &sk); 83 | 84 | return 0; 85 | }; 86 | 87 | static int trace_connect_return(struct pt_regs *ctx, short ipver) 88 | { 89 | int ret = PT_REGS_RC(ctx); 90 | u64 pid_tgid = bpf_get_current_pid_tgid(); 91 | u32 pid = pid_tgid >> 32; 92 | u32 tid = pid_tgid; 93 | 94 | struct sock **skpp; 95 | skpp = currsock.lookup(&tid); 96 | if (skpp == 0) 97 | { 98 | return 0; // missed entry 99 | } 100 | 101 | if (ret != 0) 102 | { 103 | // failed to send SYNC packet, may not have populated 104 | // socket __sk_common.{skc_rcv_saddr, ...} 105 | currsock.delete(&tid); 106 | return 0; 107 | } 108 | 109 | // pull in details 110 | struct sock *skp = *skpp; 111 | u16 lport = skp->__sk_common.skc_num; 112 | u16 dport = skp->__sk_common.skc_dport; 113 | 114 | if (ipver == 4) 115 | { 116 | 117 | struct ipv4_data_t data4 = {.pid = pid, .ip = ipver}; 118 | data4.uid = bpf_get_current_uid_gid(); 119 | data4.ts_us = bpf_ktime_get_ns() / 1000; 120 | data4.saddr = skp->__sk_common.skc_rcv_saddr; 121 | data4.daddr = skp->__sk_common.skc_daddr; 122 | data4.lport = lport; 123 | data4.dport = ntohs(dport); 124 | bpf_get_current_comm(&data4.task, sizeof(data4.task)); 125 | ipv4_events.perf_submit(ctx, &data4, sizeof(data4)); 126 | } 127 | else /* 6 */ 128 | { 129 | 130 | struct ipv6_data_t data6 = {.pid = pid, .ip = ipver}; 131 | data6.uid = bpf_get_current_uid_gid(); 132 | data6.ts_us = bpf_ktime_get_ns() / 1000; 133 | bpf_probe_read_kernel(&data6.saddr, sizeof(data6.saddr), 134 | skp->__sk_common.skc_v6_rcv_saddr.in6_u.u6_addr32); 135 | bpf_probe_read_kernel(&data6.daddr, sizeof(data6.daddr), 136 | skp->__sk_common.skc_v6_daddr.in6_u.u6_addr32); 137 | data6.lport = lport; 138 | data6.dport = ntohs(dport); 139 | bpf_get_current_comm(&data6.task, sizeof(data6.task)); 140 | ipv6_events.perf_submit(ctx, &data6, sizeof(data6)); 141 | } 142 | 143 | currsock.delete(&tid); 144 | 145 | return 0; 146 | } 147 | 148 | int trace_connect_v4_return(struct pt_regs *ctx) 149 | { 150 | return trace_connect_return(ctx, 4); 151 | } 152 | 153 | int trace_connect_v6_return(struct pt_regs *ctx) 154 | { 155 | return trace_connect_return(ctx, 6); 156 | } -------------------------------------------------------------------------------- /scripts/build_script.py: -------------------------------------------------------------------------------- 1 | from bcc import BPF 2 | 3 | bpf_text = """ 4 | #include 5 | #include 6 | #include 7 | struct val_t { 8 | u64 id; 9 | char comm[TASK_COMM_LEN]; 10 | const char *fname; 11 | int flags; // EXTENDED_STRUCT_MEMBER 12 | }; 13 | struct data_t { 14 | u64 id; 15 | u64 ts; 16 | u32 uid; 17 | int ret; 18 | char comm[TASK_COMM_LEN]; 19 | char fname[NAME_MAX]; 20 | int flags; // EXTENDED_STRUCT_MEMBER 21 | }; 22 | BPF_PERF_OUTPUT(events); 23 | """ 24 | 25 | bpf_text_kprobe = """ 26 | BPF_HASH(infotmp, u64, struct val_t); 27 | int trace_return(struct pt_regs *ctx) 28 | { 29 | u64 id = bpf_get_current_pid_tgid(); 30 | struct val_t *valp; 31 | struct data_t data = {}; 32 | u64 tsp = bpf_ktime_get_ns(); 33 | valp = infotmp.lookup(&id); 34 | if (valp == 0) { 35 | // missed entry 36 | return 0; 37 | } 38 | bpf_probe_read_kernel(&data.comm, sizeof(data.comm), valp->comm); 39 | bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)valp->fname); 40 | data.id = valp->id; 41 | data.ts = tsp / 1000; 42 | data.uid = bpf_get_current_uid_gid(); 43 | data.flags = valp->flags; // EXTENDED_STRUCT_MEMBER 44 | data.ret = PT_REGS_RC(ctx); 45 | events.perf_submit(ctx, &data, sizeof(data)); 46 | infotmp.delete(&id); 47 | return 0; 48 | } 49 | """ 50 | 51 | bpf_text_kprobe_header_open = """ 52 | int syscall__trace_entry_open(struct pt_regs *ctx, const char __user *filename, int flags) 53 | { 54 | """ 55 | 56 | bpf_text_kprobe_header_openat = """ 57 | int syscall__trace_entry_openat(struct pt_regs *ctx, int dfd, const char __user *filename, int flags) 58 | { 59 | """ 60 | 61 | bpf_text_kprobe_header_openat2 = """ 62 | #include 63 | int syscall__trace_entry_openat2(struct pt_regs *ctx, int dfd, const char __user *filename, struct open_how *how) 64 | { 65 | int flags = how->flags; 66 | """ 67 | 68 | bpf_text_kprobe_body = """ 69 | struct val_t val = {}; 70 | u64 id = bpf_get_current_pid_tgid(); 71 | u32 pid = id >> 32; // PID is higher part 72 | u32 tid = id; // Cast and get the lower part 73 | u32 uid = bpf_get_current_uid_gid(); 74 | if (bpf_get_current_comm(&val.comm, sizeof(val.comm)) == 0) { 75 | val.id = id; 76 | val.fname = filename; 77 | val.flags = flags; // EXTENDED_STRUCT_MEMBER 78 | infotmp.update(&id, &val); 79 | } 80 | return 0; 81 | }; 82 | """ 83 | 84 | bpf_text_kfunc_header_open = """ 85 | #if defined(CONFIG_ARCH_HAS_SYSCALL_WRAPPER) && !defined(__s390x__) 86 | KRETFUNC_PROBE(FNNAME, struct pt_regs *regs, int ret) 87 | { 88 | const char __user *filename = (char *)PT_REGS_PARM1(regs); 89 | int flags = PT_REGS_PARM2(regs); 90 | #else 91 | KRETFUNC_PROBE(FNNAME, const char __user *filename, int flags, int ret) 92 | { 93 | #endif 94 | """ 95 | 96 | bpf_text_kfunc_header_openat = """ 97 | #if defined(CONFIG_ARCH_HAS_SYSCALL_WRAPPER) && !defined(__s390x__) 98 | KRETFUNC_PROBE(FNNAME, struct pt_regs *regs, int ret) 99 | { 100 | int dfd = PT_REGS_PARM1(regs); 101 | const char __user *filename = (char *)PT_REGS_PARM2(regs); 102 | int flags = PT_REGS_PARM3(regs); 103 | #else 104 | KRETFUNC_PROBE(FNNAME, int dfd, const char __user *filename, int flags, int ret) 105 | { 106 | #endif 107 | """ 108 | 109 | bpf_text_kfunc_header_openat2 = """ 110 | #include 111 | #if defined(CONFIG_ARCH_HAS_SYSCALL_WRAPPER) && !defined(__s390x__) 112 | KRETFUNC_PROBE(FNNAME, struct pt_regs *regs, int ret) 113 | { 114 | int dfd = PT_REGS_PARM1(regs); 115 | const char __user *filename = (char *)PT_REGS_PARM2(regs); 116 | struct open_how __user how; 117 | int flags; 118 | bpf_probe_read_user(&how, sizeof(struct open_how), (struct open_how*)PT_REGS_PARM3(regs)); 119 | flags = how.flags; 120 | #else 121 | KRETFUNC_PROBE(FNNAME, int dfd, const char __user *filename, struct open_how __user *how, int ret) 122 | { 123 | int flags = how->flags; 124 | #endif 125 | """ 126 | 127 | bpf_text_kfunc_body = """ 128 | u64 id = bpf_get_current_pid_tgid(); 129 | u32 pid = id >> 32; // PID is higher part 130 | u32 tid = id; // Cast and get the lower part 131 | u32 uid = bpf_get_current_uid_gid(); 132 | struct data_t data = {}; 133 | bpf_get_current_comm(&data.comm, sizeof(data.comm)); 134 | u64 tsp = bpf_ktime_get_ns(); 135 | bpf_probe_read_user(&data.fname, sizeof(data.fname), (void *)filename); 136 | data.id = id; 137 | data.ts = tsp / 1000; 138 | data.uid = bpf_get_current_uid_gid(); 139 | data.flags = flags; // EXTENDED_STRUCT_MEMBER 140 | data.ret = ret; 141 | events.perf_submit(ctx, &data, sizeof(data)); 142 | return 0; 143 | } 144 | """ 145 | 146 | b = BPF(text='') 147 | fnname_open = b.get_syscall_prefix().decode() + 'open' 148 | fnname_openat = b.get_syscall_prefix().decode() + 'openat' 149 | fnname_openat2 = b.get_syscall_prefix().decode() + 'openat2' 150 | 151 | if b.ksymname(fnname_openat2) == -1: 152 | fnname_openat2 = None 153 | 154 | bpf_text += bpf_text_kprobe 155 | 156 | bpf_text += bpf_text_kprobe_header_open 157 | bpf_text += bpf_text_kprobe_body 158 | 159 | bpf_text += bpf_text_kprobe_header_openat 160 | bpf_text += bpf_text_kprobe_body 161 | 162 | if fnname_openat2: 163 | bpf_text += bpf_text_kprobe_header_openat2 164 | bpf_text += bpf_text_kprobe_body 165 | 166 | with open('probes/opensnoop.c', 'w') as f: 167 | f.write(bpf_text) 168 | 169 | build_script = """fn main() { 170 | println!("cargo:rustc-env=EXEC_FUNC=EXEC_FUNC_REPLACE"); 171 | println!("cargo:rustc-env=SYSCALL_PREFIX=SYSCALL_PREFIX_REPLACE"); 172 | println!("cargo:rustc-env=OPENAT2_CHECK=OPENAT2_CHECK_REPLACE"); 173 | }""" 174 | 175 | fnname_openat2 = b.get_syscall_prefix().decode() + 'openat2' 176 | if b.ksymname(fnname_openat2) == -1: 177 | build_script = build_script.replace('OPENAT2_CHECK_REPLACE', 'NO') 178 | else: 179 | build_script = build_script.replace('OPENAT2_CHECK_REPLACE', 'YES') 180 | 181 | build_script = build_script.replace('EXEC_FUNC_REPLACE', b.get_syscall_fnname("execve").decode()) 182 | build_script = build_script.replace('SYSCALL_PREFIX_REPLACE', b.get_syscall_prefix().decode()) 183 | 184 | with open('build.rs', 'w') as f: 185 | f.write(build_script) -------------------------------------------------------------------------------- /src/cli/check.rs: -------------------------------------------------------------------------------- 1 | use crate::visualization::{connect, exec, open}; 2 | use std::process::exit; 3 | 4 | pub fn exec(id: &str, command: Option<&str>) { 5 | if command.is_none() { 6 | print_commands(); 7 | exit(0); 8 | } 9 | 10 | match command.unwrap() { 11 | "graph" => { 12 | let graph = exec::graph(id).unwrap(); 13 | println!("Generated exec graph in {}", graph); 14 | } 15 | "ps" => { 16 | exec::ps(id); 17 | } 18 | "fs" => { 19 | open::fs(id); 20 | } 21 | "v4" => { 22 | connect::v4(id); 23 | } 24 | "v6" => { 25 | connect::v6(id); 26 | } 27 | _ => { 28 | println!("Unknown command {}", command.unwrap()); 29 | print_commands(); 30 | exit(1); 31 | } 32 | } 33 | } 34 | 35 | fn print_commands() { 36 | println!("Available commands:"); 37 | println!(" ps: print process list"); 38 | println!(" fs: print file access list (.so file omited)"); 39 | println!(" graph: generate ps graph"); 40 | println!(" v4: show IPv4 TCP connections"); 41 | println!(" v6: show IPv6 TCP connections"); 42 | } 43 | -------------------------------------------------------------------------------- /src/cli/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod check; 2 | 3 | use clap::{arg, command, ArgMatches, Command}; 4 | 5 | pub struct Cli {} 6 | 7 | impl Cli { 8 | pub fn matches() -> ArgMatches { 9 | let matches = command!() 10 | .propagate_version(true) 11 | .subcommand( 12 | Command::new("watch") 13 | .about("Watch a process and log its events") 14 | .arg(arg!( "PID of the process to watch")), 15 | ) 16 | .subcommand( 17 | Command::new("check") 18 | .about("Check previous log") 19 | .arg(arg!( "Number of the directory to analyse")) 20 | .arg(arg!([Command] "Command to run, empty for full list")), 21 | ) 22 | .get_matches(); 23 | 24 | matches 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /src/ebpf/execsnoop.rs: -------------------------------------------------------------------------------- 1 | use super::types::EventEnum; 2 | use super::utils::*; 3 | use super::AbtractProbe; 4 | use anyhow::Result; 5 | use bcc::perf_event::PerfMapBuilder; 6 | use bcc::{Kprobe, Kretprobe, BPF}; 7 | use futures::executor::block_on; 8 | use futures::lock::Mutex; 9 | use lockfree::channel::mpsc::Sender; 10 | use std::sync::{Arc, Once}; 11 | 12 | static mut SENDER: Option> = None; 13 | static LOAD_INIT: Once = Once::new(); 14 | const EXEC_FUNC: &str = env!("EXEC_FUNC"); 15 | 16 | pub struct Probe {} 17 | 18 | impl AbtractProbe for Probe { 19 | fn load(sender: Sender, completed_probes: Arc>) -> Result<()> { 20 | LOAD_INIT.call_once(|| unsafe { 21 | SENDER = Some(sender); 22 | }); 23 | let code = include_str!("../../probes/execsnoop.c"); 24 | let mut module = BPF::new(code)?; 25 | 26 | Kprobe::new() 27 | .handler("syscall__execve") 28 | .function(EXEC_FUNC) 29 | .attach(&mut module)?; 30 | Kretprobe::new() 31 | .handler("do_ret_sys_execve") 32 | .function(EXEC_FUNC) 33 | .attach(&mut module)?; 34 | 35 | let table = module.table("events").unwrap(); 36 | 37 | let mut perf_map = PerfMapBuilder::new(table, callback).build().unwrap(); 38 | 39 | let mut completed_guard = block_on(completed_probes.lock()); 40 | *completed_guard += 1; 41 | drop(completed_guard); 42 | 43 | loop { 44 | perf_map.poll(100); 45 | } 46 | } 47 | } 48 | 49 | #[repr(C)] 50 | #[derive(Debug)] 51 | #[allow(dead_code)] 52 | pub enum EventType { 53 | Arg, 54 | Ret, 55 | } 56 | 57 | #[repr(C)] 58 | #[derive(Debug)] 59 | pub struct Event { 60 | pub pid: u32, 61 | pub ppid: u32, 62 | pub uid: u32, 63 | pub comm: [u8; 16], 64 | pub event_type: EventType, 65 | pub argv: [u8; 128], 66 | pub ret: libc::c_int, 67 | } 68 | 69 | fn callback() -> Box { 70 | Box::new(|x| { 71 | let data: Event = read_struct(x); 72 | unsafe { 73 | let tx = SENDER.as_ref().unwrap().clone(); 74 | tx.send(EventEnum::Exec(data)).unwrap(); 75 | } 76 | }) 77 | } 78 | -------------------------------------------------------------------------------- /src/ebpf/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod execsnoop; 2 | pub mod opensnoop; 3 | pub mod tcpconnect; 4 | pub mod types; 5 | pub mod utils; 6 | 7 | use crate::storage::types::*; 8 | use anyhow::Result; 9 | use futures::lock::Mutex; 10 | use lockfree::channel::mpsc; 11 | use std::collections::HashMap; 12 | use std::sync::Arc; 13 | use tokio::time::{sleep, Duration}; 14 | 15 | type ArgvMap = HashMap; 16 | 17 | pub trait AbtractProbe { 18 | fn load( 19 | sender: mpsc::Sender, 20 | completed_probes: Arc>, 21 | ) -> Result<()>; 22 | } 23 | 24 | pub async fn load(storage_sender: mpsc::Sender) -> Result<()> { 25 | let mut exec_argv_map = ArgvMap::new(); 26 | 27 | let (sender, mut receiver) = mpsc::create(); 28 | let exec_sender = sender.clone(); 29 | let open_sender = sender.clone(); 30 | let tcp_sender = sender.clone(); 31 | let completed_probes = Arc::new(Mutex::new(0)); 32 | let exec_com = completed_probes.clone(); 33 | let open_com = exec_com.clone(); 34 | let tcp_com = exec_com.clone(); 35 | tokio::spawn(async move { 36 | if let Err(e) = execsnoop::Probe::load(exec_sender, exec_com) { 37 | panic!("Failed to load ecec eBPF: {}", e); 38 | } 39 | }); 40 | tokio::spawn(async move { 41 | if let Err(e) = opensnoop::Probe::load(open_sender, open_com) { 42 | panic!("Failed to load open eBPF: {}", e); 43 | } 44 | }); 45 | tokio::spawn(async move { 46 | if let Err(e) = tcpconnect::Probe::load(tcp_sender, tcp_com) { 47 | panic!("Failed to load tcp eBPF: {}", e); 48 | } 49 | }); 50 | println!("Waiting for building eBPF..."); 51 | loop { 52 | let completed_guard = completed_probes.lock().await; 53 | if *completed_guard == 3 { 54 | drop(completed_guard); 55 | break; 56 | } else { 57 | println!("{}/3 probes built", *completed_guard); 58 | drop(completed_guard); 59 | sleep(Duration::from_millis(5000)).await; 60 | } 61 | } 62 | println!("eBPF is ready"); 63 | loop { 64 | if let Ok(message) = receiver.recv() { 65 | match message { 66 | types::EventEnum::Exec(event) => { 67 | let argv = exec_argv_map.entry(event.pid).or_insert_with(String::new); 68 | match event.event_type { 69 | execsnoop::EventType::Arg => { 70 | argv.push_str(&format!("{} ", utils::read_u8_string(&event.argv))); 71 | } 72 | execsnoop::EventType::Ret => { 73 | argv.pop(); 74 | let send_event = ExecEvent { 75 | pid: event.pid, 76 | ppid: event.ppid, 77 | uid: event.uid, 78 | command: utils::read_u8_string(&event.comm), 79 | argv: argv.clone(), 80 | }; 81 | storage_sender.send(EventType::Exec(send_event)).unwrap(); 82 | exec_argv_map.remove(&event.pid); 83 | } 84 | } 85 | } 86 | types::EventEnum::Open(event) => { 87 | let pid: u32 = (event.id >> 32) as u32; 88 | let send_event = OpenEvent { 89 | pid, 90 | ts: event.ts, 91 | uid: event.uid, 92 | command: utils::read_u8_string(&event.comm), 93 | fname: utils::read_u8_string(&event.fname), 94 | }; 95 | storage_sender.send(EventType::Open(send_event)).unwrap(); 96 | } 97 | types::EventEnum::ConnectV4(event) => { 98 | let send_event = ConnectV4Event { 99 | pid: event.pid, 100 | ts: event.ts_us, 101 | uid: event.uid, 102 | task: utils::read_u8_string(&event.task), 103 | saddr: u32::from_be(event.saddr).into(), 104 | daddr: u32::from_be(event.daddr).into(), 105 | lport: event.lport, 106 | dport: event.dport, 107 | }; 108 | storage_sender 109 | .send(EventType::ConnectV4(send_event)) 110 | .unwrap(); 111 | } 112 | types::EventEnum::ConnectV6(event) => { 113 | let send_event = ConnectV6Event { 114 | pid: event.pid, 115 | ts: event.ts_us, 116 | uid: event.uid, 117 | task: utils::read_u8_string(&event.task), 118 | saddr: u128::from_be(event.saddr).into(), 119 | daddr: u128::from_be(event.daddr).into(), 120 | lport: event.lport, 121 | dport: event.dport, 122 | }; 123 | storage_sender 124 | .send(EventType::ConnectV6(send_event)) 125 | .unwrap(); 126 | } 127 | } 128 | } else { 129 | sleep(Duration::from_millis(1000)).await; 130 | } 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/ebpf/opensnoop.rs: -------------------------------------------------------------------------------- 1 | use super::types::EventEnum; 2 | use super::utils::*; 3 | use super::AbtractProbe; 4 | use anyhow::Result; 5 | use bcc::perf_event::PerfMapBuilder; 6 | use bcc::{Kprobe, Kretprobe, BPF}; 7 | use futures::executor::block_on; 8 | use futures::lock::Mutex; 9 | use lockfree::channel::mpsc::Sender; 10 | use std::sync::{Arc, Once}; 11 | use tokio::time::{sleep, Duration}; 12 | 13 | static mut SENDER: Option> = None; 14 | static LOAD_INIT: Once = Once::new(); 15 | const SYSCALL_PREFIX: &str = env!("SYSCALL_PREFIX"); 16 | const OPENAT2_CHECK: &str = env!("OPENAT2_CHECK"); 17 | 18 | pub struct Probe {} 19 | 20 | impl AbtractProbe for Probe { 21 | fn load(sender: Sender, completed_probes: Arc>) -> Result<()> { 22 | loop { 23 | let completed_guard = block_on(completed_probes.lock()); 24 | if *completed_guard == 1 { 25 | drop(completed_guard); 26 | break; 27 | } else { 28 | drop(completed_guard); 29 | block_on(sleep(Duration::from_millis(1000))); 30 | } 31 | } 32 | 33 | LOAD_INIT.call_once(|| unsafe { 34 | SENDER = Some(sender); 35 | }); 36 | let code = include_str!("../../probes/opensnoop.c"); 37 | let fname_open = format!("{}open", SYSCALL_PREFIX); 38 | let fnname_openat = format!("{}openat", SYSCALL_PREFIX); 39 | let fnname_openat2 = format!("{}openat2", SYSCALL_PREFIX); 40 | let mut module = BPF::new(code)?; 41 | Kprobe::new() 42 | .handler("syscall__trace_entry_open") 43 | .function(&fname_open) 44 | .attach(&mut module)?; 45 | Kretprobe::new() 46 | .handler("trace_return") 47 | .function(&fname_open) 48 | .attach(&mut module)?; 49 | Kprobe::new() 50 | .handler("syscall__trace_entry_openat") 51 | .function(&fnname_openat) 52 | .attach(&mut module)?; 53 | Kretprobe::new() 54 | .handler("trace_return") 55 | .function(&fnname_openat) 56 | .attach(&mut module)?; 57 | if OPENAT2_CHECK.eq("YES") { 58 | Kprobe::new() 59 | .handler("syscall__trace_entry_openat2") 60 | .function(&fnname_openat2) 61 | .attach(&mut module)?; 62 | Kretprobe::new() 63 | .handler("trace_return") 64 | .function(&fnname_openat2) 65 | .attach(&mut module)?; 66 | } 67 | let table = module.table("events").unwrap(); 68 | 69 | let mut perf_map = PerfMapBuilder::new(table, callback).build().unwrap(); 70 | 71 | let mut completed_guard = block_on(completed_probes.lock()); 72 | *completed_guard += 1; 73 | drop(completed_guard); 74 | 75 | loop { 76 | perf_map.poll(103); 77 | } 78 | } 79 | } 80 | 81 | #[repr(C)] 82 | #[derive(Debug)] 83 | pub struct Event { 84 | pub id: u64, 85 | pub ts: u64, 86 | pub uid: u32, 87 | pub ret: libc::c_int, 88 | pub comm: [u8; 16], 89 | pub fname: [u8; 255], 90 | } 91 | 92 | fn callback() -> Box { 93 | Box::new(|x| { 94 | let data: Event = read_struct(x); 95 | unsafe { 96 | let tx = SENDER.as_ref().unwrap().clone(); 97 | tx.send(EventEnum::Open(data)).unwrap(); 98 | } 99 | }) 100 | } 101 | -------------------------------------------------------------------------------- /src/ebpf/tcpconnect.rs: -------------------------------------------------------------------------------- 1 | use super::types::EventEnum; 2 | use super::utils::*; 3 | use super::AbtractProbe; 4 | use anyhow::Result; 5 | use bcc::perf_event::PerfMapBuilder; 6 | use bcc::{Kprobe, Kretprobe, BPF}; 7 | use futures::executor::block_on; 8 | use futures::lock::Mutex; 9 | use lockfree::channel::mpsc::Sender; 10 | use std::sync::{Arc, Once}; 11 | use tokio::time::{sleep, Duration}; 12 | 13 | static mut SENDER: Option> = None; 14 | static LOAD_INIT: Once = Once::new(); 15 | 16 | pub struct Probe {} 17 | 18 | impl AbtractProbe for Probe { 19 | fn load(sender: Sender, completed_probes: Arc>) -> Result<()> { 20 | loop { 21 | let completed_guard = block_on(completed_probes.lock()); 22 | if *completed_guard == 2 { 23 | drop(completed_guard); 24 | break; 25 | } else { 26 | drop(completed_guard); 27 | block_on(sleep(Duration::from_millis(1000))); 28 | } 29 | } 30 | 31 | LOAD_INIT.call_once(|| unsafe { 32 | SENDER = Some(sender); 33 | }); 34 | let code = include_str!("../../probes/tcpconnect.c"); 35 | let mut module = BPF::new(code)?; 36 | Kprobe::new() 37 | .handler("trace_connect_entry") 38 | .function("tcp_v4_connect") 39 | .attach(&mut module)?; 40 | Kprobe::new() 41 | .handler("trace_connect_entry") 42 | .function("tcp_v6_connect") 43 | .attach(&mut module)?; 44 | Kretprobe::new() 45 | .handler("trace_connect_v4_return") 46 | .function("tcp_v4_connect") 47 | .attach(&mut module)?; 48 | Kretprobe::new() 49 | .handler("trace_connect_v6_return") 50 | .function("tcp_v6_connect") 51 | .attach(&mut module)?; 52 | 53 | let v4_table = module.table("ipv4_events").unwrap(); 54 | let v6_table = module.table("ipv6_events").unwrap(); 55 | 56 | let mut v4_perf_map = PerfMapBuilder::new(v4_table, v4_callback).build().unwrap(); 57 | let mut v6_perf_map = PerfMapBuilder::new(v6_table, v6_callback).build().unwrap(); 58 | 59 | let mut completed_guard = block_on(completed_probes.lock()); 60 | *completed_guard += 1; 61 | drop(completed_guard); 62 | 63 | loop { 64 | v4_perf_map.poll(200); 65 | v6_perf_map.poll(200); 66 | } 67 | } 68 | } 69 | 70 | #[repr(C)] 71 | #[derive(Debug)] 72 | pub struct V4Event { 73 | pub ts_us: u64, 74 | pub pid: u32, 75 | pub uid: u32, 76 | pub saddr: u32, 77 | pub daddr: u32, 78 | pub ip: u64, 79 | pub lport: u16, 80 | pub dport: u16, 81 | pub task: [u8; 16], 82 | } 83 | 84 | #[repr(C)] 85 | #[derive(Debug)] 86 | pub struct V6Event { 87 | pub ts_us: u64, 88 | pub pid: u32, 89 | pub uid: u32, 90 | pub saddr: u128, 91 | pub daddr: u128, 92 | pub ip: u64, 93 | pub lport: u16, 94 | pub dport: u16, 95 | pub task: [u8; 16], 96 | } 97 | 98 | fn v4_callback() -> Box { 99 | Box::new(|x| { 100 | let data: V4Event = read_struct(x); 101 | unsafe { 102 | let tx = SENDER.as_ref().unwrap().clone(); 103 | tx.send(EventEnum::ConnectV4(data)).unwrap(); 104 | } 105 | }) 106 | } 107 | 108 | fn v6_callback() -> Box { 109 | Box::new(|x| { 110 | let data: V6Event = read_struct(x); 111 | unsafe { 112 | let tx = SENDER.as_ref().unwrap().clone(); 113 | tx.send(EventEnum::ConnectV6(data)).unwrap(); 114 | } 115 | }) 116 | } 117 | -------------------------------------------------------------------------------- /src/ebpf/types.rs: -------------------------------------------------------------------------------- 1 | #[derive(Debug)] 2 | pub enum EventEnum { 3 | Exec(super::execsnoop::Event), 4 | Open(super::opensnoop::Event), 5 | ConnectV4(super::tcpconnect::V4Event), 6 | ConnectV6(super::tcpconnect::V6Event), 7 | } 8 | -------------------------------------------------------------------------------- /src/ebpf/utils.rs: -------------------------------------------------------------------------------- 1 | use std::ptr; 2 | 3 | pub fn read_struct(x: &[u8]) -> T { 4 | unsafe { ptr::read_unaligned(x.as_ptr() as *const T) } 5 | } 6 | 7 | pub fn read_u8_string(x: &[u8]) -> String { 8 | match x.iter().position(|&r| r == 0) { 9 | Some(zero_pos) => String::from_utf8_lossy(&x[0..zero_pos]).to_string(), 10 | None => String::from_utf8_lossy(x).to_string(), 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | mod cli; 2 | mod ebpf; 3 | mod server; 4 | mod storage; 5 | mod visualization; 6 | 7 | use cli::Cli; 8 | 9 | #[tokio::main] 10 | async fn main() { 11 | storage::utils::ensure_directories(); 12 | 13 | let args = Cli::matches(); 14 | 15 | if let Some(matches) = args.subcommand_matches("watch") { 16 | let pid = matches.value_of("PID").unwrap().parse::().unwrap(); 17 | println!("Watching PID {}", pid); 18 | server::start(pid).await; 19 | } else if let Some(matches) = args.subcommand_matches("check") { 20 | cli::check::exec(matches.value_of("Id").unwrap(), matches.value_of("Command")); 21 | } else { 22 | println!("No command specified, use --help for more information."); 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/server.rs: -------------------------------------------------------------------------------- 1 | use crate::ebpf; 2 | use lockfree::channel::mpsc; 3 | 4 | pub async fn start(pid: u32) { 5 | let (sender, receiver) = mpsc::create(); 6 | 7 | let load_handler = tokio::spawn(async move { 8 | let res = ebpf::load(sender).await; 9 | if let Err(e) = res { 10 | println!("Failed to load eBPF: {}", e); 11 | } 12 | }); 13 | 14 | let logger_handler = tokio::spawn(async move { 15 | let res = crate::storage::log::event_logger(receiver, pid).await; 16 | if let Err(e) = res { 17 | println!("Logger exited with error: {}", e); 18 | } 19 | }); 20 | 21 | let _ = tokio::try_join!(load_handler, logger_handler).unwrap(); 22 | } 23 | -------------------------------------------------------------------------------- /src/storage/log.rs: -------------------------------------------------------------------------------- 1 | use super::types::*; 2 | use super::utils::{create_log_file, fliter_so_file}; 3 | use anyhow::Result; 4 | use lockfree::channel::mpsc; 5 | use std::fs; 6 | use tokio::time::{sleep, Duration}; 7 | 8 | pub async fn event_logger(mut receiver: mpsc::Receiver, pid: u32) -> Result<()> { 9 | let event_db = sled::open("/var/lib/foxear/logs/db")?; 10 | let last_id: u8 = match event_db.get(b"last_id")? { 11 | Some(id) => *id.first().unwrap(), 12 | None => 0, 13 | } + 1; 14 | event_db.insert(b"last_id", &[last_id]).unwrap(); 15 | let log_dir = format!("/var/lib/foxear/logs/{}", last_id); 16 | println!("Logs are stored at {}", log_dir); 17 | fs::create_dir_all(&log_dir).unwrap(); 18 | 19 | let mut watch_pid: Vec = vec![pid]; 20 | 21 | loop { 22 | if let Ok(event) = receiver.recv() { 23 | let (event_type, header) = match event { 24 | EventType::Exec(_) => ("exec", "pid,ppid,uid,command,argv\n"), 25 | EventType::Open(_) => ("open", "pid,ts,uid,command,fname\n"), 26 | EventType::ConnectV4(_) => { 27 | ("tcp_connectv4", "ts,pid,uid,saddr,daddr,lport,dport,task\n") 28 | } 29 | EventType::ConnectV6(_) => { 30 | ("tcp_connectv6", "ts,pid,uid,saddr,daddr,lport,dport,task\n") 31 | } 32 | }; 33 | let log_path = format!("{}/{}.csv", log_dir, event_type); 34 | let log_file = create_log_file(&log_path, header); 35 | let mut csv_writer = csv::WriterBuilder::new() 36 | .has_headers(false) 37 | .from_writer(log_file); 38 | match event { 39 | EventType::Exec(event) => { 40 | if watch_pid.contains(&event.ppid) { 41 | watch_pid.push(event.pid); 42 | println!( 43 | "Process {} created subprocess {}: {}", 44 | event.ppid, event.pid, event.command 45 | ); 46 | } 47 | if watch_pid.contains(&event.pid) { 48 | csv_writer.serialize(&event)?; 49 | csv_writer.flush()?; 50 | } 51 | } 52 | EventType::Open(event) => { 53 | if watch_pid.contains(&event.pid) { 54 | if !fliter_so_file(&event.fname) { 55 | println!( 56 | "Process {} {} try to access: {}", 57 | event.pid, event.command, event.fname 58 | ); 59 | } 60 | csv_writer.serialize(&event)?; 61 | csv_writer.flush()?; 62 | } 63 | } 64 | EventType::ConnectV4(event) => { 65 | if watch_pid.contains(&event.pid) { 66 | println!( 67 | "Process {} {} try to connect: {}:{}", 68 | event.pid, event.task, event.daddr, event.dport 69 | ); 70 | csv_writer.serialize(&event)?; 71 | csv_writer.flush()?; 72 | } 73 | } 74 | EventType::ConnectV6(event) => { 75 | if watch_pid.contains(&event.pid) { 76 | println!( 77 | "Process {} {} try to connect: [{}]:{}", 78 | event.pid, event.task, event.daddr, event.dport 79 | ); 80 | csv_writer.serialize(&event)?; 81 | csv_writer.flush()?; 82 | } 83 | } 84 | }; 85 | } else { 86 | sleep(Duration::from_millis(1000)).await; 87 | } 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/storage/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod log; 2 | pub mod types; 3 | pub mod utils; 4 | -------------------------------------------------------------------------------- /src/storage/types.rs: -------------------------------------------------------------------------------- 1 | use serde::{Deserialize, Serialize}; 2 | use std::net::{Ipv4Addr, Ipv6Addr}; 3 | 4 | #[derive(Debug)] 5 | pub enum EventType { 6 | Exec(ExecEvent), 7 | Open(OpenEvent), 8 | ConnectV4(ConnectV4Event), 9 | ConnectV6(ConnectV6Event), 10 | } 11 | 12 | #[derive(Debug, Clone, Serialize, Deserialize)] 13 | pub struct ExecEvent { 14 | pub pid: u32, 15 | pub ppid: u32, 16 | pub uid: u32, 17 | pub command: String, 18 | pub argv: String, 19 | } 20 | 21 | #[derive(Debug, Clone, Serialize, Deserialize)] 22 | pub struct OpenEvent { 23 | pub pid: u32, 24 | pub ts: u64, 25 | pub uid: u32, 26 | pub command: String, 27 | pub fname: String, 28 | } 29 | 30 | #[derive(Debug, Clone, Serialize, Deserialize)] 31 | pub struct ConnectV4Event { 32 | pub ts: u64, 33 | pub pid: u32, 34 | pub uid: u32, 35 | pub saddr: Ipv4Addr, 36 | pub daddr: Ipv4Addr, 37 | pub lport: u16, 38 | pub dport: u16, 39 | pub task: String, 40 | } 41 | 42 | #[derive(Debug, Clone, Serialize, Deserialize)] 43 | pub struct ConnectV6Event { 44 | pub ts: u64, 45 | pub pid: u32, 46 | pub uid: u32, 47 | pub saddr: Ipv6Addr, 48 | pub daddr: Ipv6Addr, 49 | pub lport: u16, 50 | pub dport: u16, 51 | pub task: String, 52 | } 53 | -------------------------------------------------------------------------------- /src/storage/utils.rs: -------------------------------------------------------------------------------- 1 | use std::fs::{self, OpenOptions}; 2 | use std::io::Write; 3 | use std::path::Path; 4 | 5 | pub const LOG_DIR: &str = "/var/lib/foxear/logs"; 6 | 7 | pub fn ensure_directories() { 8 | fs::create_dir_all(LOG_DIR).unwrap(); 9 | } 10 | 11 | pub fn create_log_file(path: &str, header: &str) -> fs::File { 12 | let exist = Path::new(path).exists(); 13 | let mut log_file = OpenOptions::new() 14 | .write(true) 15 | .append(true) 16 | .create(true) 17 | .open(path) 18 | .unwrap(); 19 | if !exist { 20 | log_file.write_all(header.as_bytes()).unwrap(); 21 | } 22 | log_file 23 | } 24 | 25 | pub fn fliter_so_file(path: &str) -> bool { 26 | let path = Path::new(path); 27 | if let Some(extension) = path.extension() { 28 | if extension == "so" { 29 | return true; 30 | } 31 | } 32 | if let Some(file_stem) = path.file_stem() { 33 | if let Some(file_stem) = file_stem.to_str() { 34 | if file_stem.contains(".so.") || file_stem.ends_with(".so") { 35 | return true; 36 | } 37 | } 38 | } 39 | false 40 | } 41 | -------------------------------------------------------------------------------- /src/visualization/connect.rs: -------------------------------------------------------------------------------- 1 | use super::utils::ensure_exists; 2 | use crate::storage::types::{ConnectV4Event, ConnectV6Event}; 3 | use crate::storage::utils::LOG_DIR; 4 | use cli_table::{print_stdout, Table, WithTitle}; 5 | use std::fs::OpenOptions; 6 | 7 | #[derive(Table)] 8 | struct Output { 9 | pub pid: u32, 10 | pub uid: u32, 11 | pub task: String, 12 | pub source: String, 13 | pub target: String, 14 | } 15 | 16 | pub fn v4(path: &str) { 17 | let log_file = format!("{}/{}/tcp_connectv4.csv", LOG_DIR, path); 18 | ensure_exists(&log_file); 19 | let log_file = OpenOptions::new().read(true).open(log_file).unwrap(); 20 | let mut rdr = csv::Reader::from_reader(log_file); 21 | let mut records = Vec::new(); 22 | 23 | for result in rdr.deserialize() { 24 | let record: ConnectV4Event = result.unwrap(); 25 | let record = Output { 26 | pid: record.pid, 27 | uid: record.uid, 28 | task: record.task, 29 | source: format!("{}:{}", record.saddr, record.lport), 30 | target: format!("{}:{}", record.daddr, record.dport), 31 | }; 32 | records.push(record); 33 | } 34 | 35 | print_stdout(records.with_title()).unwrap(); 36 | } 37 | 38 | pub fn v6(path: &str) { 39 | let log_file = format!("{}/{}/tcp_connectv6.csv", LOG_DIR, path); 40 | ensure_exists(&log_file); 41 | let log_file = OpenOptions::new().read(true).open(log_file).unwrap(); 42 | let mut rdr = csv::Reader::from_reader(log_file); 43 | let mut records = Vec::new(); 44 | 45 | for result in rdr.deserialize() { 46 | let record: ConnectV6Event = result.unwrap(); 47 | let record = Output { 48 | pid: record.pid, 49 | uid: record.uid, 50 | task: record.task, 51 | source: format!("[{}]:{}", record.saddr, record.lport), 52 | target: format!("[{}]:{}", record.daddr, record.dport), 53 | }; 54 | records.push(record); 55 | } 56 | 57 | print_stdout(records.with_title()).unwrap(); 58 | } 59 | -------------------------------------------------------------------------------- /src/visualization/exec.rs: -------------------------------------------------------------------------------- 1 | use super::utils::ensure_exists; 2 | use crate::storage::types::*; 3 | use crate::storage::utils::LOG_DIR; 4 | use anyhow::Result; 5 | use cli_table::{print_stdout, TableStruct}; 6 | use csv::ReaderBuilder; 7 | use petgraph::dot::Dot; 8 | use petgraph::graph::NodeIndex; 9 | use petgraph::Graph; 10 | use std::collections::HashMap; 11 | use std::fs::{self, OpenOptions}; 12 | use std::io::Write; 13 | 14 | pub fn ps(path: &str) { 15 | let log_file = format!("{}/{}/exec.csv", LOG_DIR, path); 16 | ensure_exists(&log_file); 17 | let log_file = OpenOptions::new().read(true).open(log_file).unwrap(); 18 | 19 | let mut reader = ReaderBuilder::new().from_reader(log_file); 20 | let table = TableStruct::try_from(&mut reader).unwrap(); 21 | 22 | print_stdout(table).unwrap(); 23 | } 24 | 25 | pub fn graph(path: &str) -> Result { 26 | let log_file = format!("{}/{}/exec.csv", LOG_DIR, path); 27 | ensure_exists(&log_file); 28 | fs::create_dir_all(format!("{}/{}/reports", LOG_DIR, path)).unwrap(); 29 | let output_file = format!("{}/{}/reports/exec.dot", LOG_DIR, path); 30 | let mut reader = csv::Reader::from_path(log_file)?; 31 | let mut deps = Graph::<&str, &str>::new(); 32 | let mut command_map: HashMap = HashMap::new(); 33 | let mut parent_map: HashMap = HashMap::new(); 34 | let mut command_relations: Vec<(NodeIndex, NodeIndex)> = Vec::new(); 35 | let mut records = Vec::new(); 36 | 37 | for result in reader.deserialize() { 38 | let mut record: ExecEvent = result?; 39 | if record.uid == 0 { 40 | record.command = format!("{} (root)", record.command); 41 | } 42 | records.push(record); 43 | } 44 | 45 | for record in &records { 46 | let node = deps.add_node(&record.command); 47 | command_map.insert(record.pid, node); 48 | parent_map.insert(record.pid, record.ppid); 49 | } 50 | 51 | for (pid, ppid) in parent_map { 52 | if let Some(parent) = command_map.get(&ppid) { 53 | command_relations.push((*parent, *command_map.get(&pid).unwrap())); 54 | } 55 | } 56 | 57 | deps.extend_with_edges(&command_relations); 58 | let dot = Dot::new(&deps); 59 | let mut file = fs::File::options() 60 | .create(true) 61 | .write(true) 62 | .open(&output_file)?; 63 | write!(file, "{}", dot)?; 64 | file.flush()?; 65 | 66 | Ok(output_file) 67 | } 68 | -------------------------------------------------------------------------------- /src/visualization/mod.rs: -------------------------------------------------------------------------------- 1 | pub mod connect; 2 | pub mod exec; 3 | pub mod open; 4 | mod utils; 5 | -------------------------------------------------------------------------------- /src/visualization/open.rs: -------------------------------------------------------------------------------- 1 | use super::utils::ensure_exists; 2 | use crate::storage::types::OpenEvent; 3 | use crate::storage::utils::fliter_so_file; 4 | use crate::storage::utils::LOG_DIR; 5 | use cli_table::{print_stdout, Table, WithTitle}; 6 | use std::fs::OpenOptions; 7 | 8 | #[derive(Table)] 9 | struct Output { 10 | pid: u32, 11 | uid: u32, 12 | command: String, 13 | #[table(title = "path")] 14 | fname: String, 15 | } 16 | 17 | pub fn fs(path: &str) { 18 | let log_file = format!("{}/{}/open.csv", LOG_DIR, path); 19 | ensure_exists(&log_file); 20 | let log_file = OpenOptions::new().read(true).open(log_file).unwrap(); 21 | let mut rdr = csv::Reader::from_reader(log_file); 22 | let mut records = Vec::new(); 23 | 24 | for result in rdr.deserialize() { 25 | let record: OpenEvent = result.unwrap(); 26 | let record = Output { 27 | pid: record.pid, 28 | uid: record.uid, 29 | command: record.command, 30 | fname: record.fname, 31 | }; 32 | if fliter_so_file(&record.fname) { 33 | continue; 34 | } 35 | records.push(record); 36 | } 37 | 38 | print_stdout(records.with_title()).unwrap(); 39 | } 40 | -------------------------------------------------------------------------------- /src/visualization/utils.rs: -------------------------------------------------------------------------------- 1 | use std::path::Path; 2 | use std::process::exit; 3 | 4 | pub fn ensure_exists(path: &str) { 5 | if !Path::new(path).exists() { 6 | println!("{} does not exist", path); 7 | exit(1); 8 | } 9 | } 10 | --------------------------------------------------------------------------------