├── .github ├── dependabot.yml └── workflows │ └── ci.yml ├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-GPL2 ├── LICENSE-MIT ├── README.md ├── cargo-generate.toml ├── pre-script.rhai ├── rustfmt.toml ├── test.sh ├── {{project-name}}-common ├── Cargo.toml └── src │ └── lib.rs ├── {{project-name}}-ebpf ├── Cargo.toml ├── build.rs └── src │ ├── lib.rs │ └── main.rs └── {{project-name}} ├── Cargo.toml ├── build.rs └── src └── main.rs /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | # Please see the documentation for all configuration options: 2 | # https://docs.github.com/en/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file 3 | 4 | version: 2 5 | updates: 6 | - package-ecosystem: "cargo" 7 | directory: "/" 8 | schedule: 9 | interval: "weekly" 10 | - package-ecosystem: "github-actions" 11 | directory: "/" 12 | schedule: 13 | interval: "weekly" 14 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | 3 | on: 4 | push: 5 | branches: 6 | - main 7 | 8 | pull_request: 9 | branches: 10 | - main 11 | 12 | schedule: 13 | - cron: 00 4 * * * 14 | 15 | env: 16 | CARGO_TERM_COLOR: always 17 | 18 | concurrency: 19 | group: ${{ github.workflow }}-${{ github.ref }} 20 | cancel-in-progress: true 21 | 22 | jobs: 23 | build: 24 | strategy: 25 | fail-fast: false 26 | matrix: 27 | runner: 28 | - ubuntu-latest # x86 29 | program: 30 | - kprobe 31 | - kretprobe 32 | - fentry 33 | - fexit 34 | - uprobe 35 | - uretprobe 36 | - sock_ops 37 | - socket_filter 38 | - sk_msg 39 | - xdp 40 | - cgroup_skb 41 | - cgroup_sockopt 42 | - cgroup_sysctl 43 | - classifier 44 | - lsm 45 | - perf_event 46 | - raw_tracepoint 47 | - tp_btf 48 | - tracepoint 49 | include: 50 | - runner: macos-13 # x86 51 | program: kprobe 52 | - runner: macos-14 # arm64 53 | program: kprobe 54 | 55 | runs-on: ${{ matrix.runner }} 56 | 57 | steps: 58 | - uses: actions/checkout@v4 59 | 60 | - uses: dtolnay/rust-toolchain@nightly 61 | with: 62 | components: clippy,rust-src,rustfmt 63 | 64 | - uses: dtolnay/rust-toolchain@stable 65 | if: runner.os == 'macOS' && runner.arch == 'X64' 66 | with: 67 | targets: x86_64-unknown-linux-musl 68 | 69 | - uses: dtolnay/rust-toolchain@stable 70 | if: runner.os == 'macOS' && runner.arch == 'ARM64' 71 | with: 72 | targets: aarch64-unknown-linux-musl 73 | 74 | - uses: dtolnay/rust-toolchain@stable 75 | if: runner.os == 'Linux' 76 | 77 | - uses: Swatinem/rust-cache@v2 78 | 79 | - uses: taiki-e/install-action@v2 80 | with: 81 | tool: cargo-generate 82 | 83 | - run: brew update && brew install filosottile/musl-cross/musl-cross llvm 84 | if: runner.os == 'macos' 85 | 86 | - run: cargo install bpf-linker --git https://github.com/aya-rs/bpf-linker.git --no-default-features 87 | if: runner.os == 'macos' 88 | 89 | - run: cargo install bpf-linker --git https://github.com/aya-rs/bpf-linker.git 90 | if: runner.os == 'Linux' 91 | 92 | - run: sudo apt update && sudo apt install expect 93 | if: runner.os == 'Linux' 94 | 95 | - run: ./test.sh ${{ github.workspace }} ${{ matrix.program }} 96 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### https://raw.github.com/github/gitignore/master/Rust.gitignore 2 | 3 | # Generated by Cargo 4 | # will have compiled files and executables 5 | debug/ 6 | target/ 7 | 8 | # These are backup files generated by rustfmt 9 | **/*.rs.bk 10 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [workspace] 2 | resolver = "2" 3 | members = [ 4 | "{{project-name}}", 5 | "{{project-name}}-common", 6 | "{{project-name}}-ebpf", 7 | ] 8 | default-members = ["{{project-name}}", "{{project-name}}-common"] 9 | 10 | [workspace.package] 11 | license = "MIT OR Apache-2.0" 12 | 13 | [workspace.dependencies] 14 | aya = { version = "0.13.1", default-features = false } 15 | aya-build = { version = "0.1.2", default-features = false } 16 | aya-ebpf = { version = "0.1.1", default-features = false } 17 | aya-log = { version = "0.2.1", default-features = false } 18 | aya-log-ebpf = { version = "0.1.1", default-features = false } 19 | 20 | anyhow = { version = "1", default-features = false } 21 | # `std` feature is currently required to build `clap`. 22 | # 23 | # See https://github.com/clap-rs/clap/blob/61f5ee5/clap_builder/src/lib.rs#L15. 24 | clap = { version = "4.5.20", default-features = false, features = ["std"] } 25 | env_logger = { version = "0.11.5", default-features = false } 26 | libc = { version = "0.2.159", default-features = false } 27 | log = { version = "0.4.22", default-features = false } 28 | tokio = { version = "1.40.0", default-features = false } 29 | which = { version = "6.0.0", default-features = false } 30 | 31 | [profile.release.package.{{project-name}}-ebpf] 32 | debug = 2 33 | codegen-units = 1 34 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 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 {yyyy} Authors of bpfman. 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 | -------------------------------------------------------------------------------- /LICENSE-GPL2: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2021 Alessandro Decina 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be 12 | included in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND 17 | NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE 18 | LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 19 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION 20 | WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 21 | 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # {{project-name}} 2 | 3 | ## Prerequisites 4 | 5 | 1. stable rust toolchains: `rustup toolchain install stable` 6 | 1. nightly rust toolchains: `rustup toolchain install nightly --component rust-src` 7 | 1. (if cross-compiling) rustup target: `rustup target add ${ARCH}-unknown-linux-musl` 8 | 1. (if cross-compiling) LLVM: (e.g.) `brew install llvm` (on macOS) 9 | 1. (if cross-compiling) C toolchain: (e.g.) [`brew install filosottile/musl-cross/musl-cross`](https://github.com/FiloSottile/homebrew-musl-cross) (on macOS) 10 | 1. bpf-linker: `cargo install bpf-linker` (`--no-default-features` on macOS) 11 | 12 | ## Build & Run 13 | 14 | Use `cargo build`, `cargo check`, etc. as normal. Run your program with: 15 | 16 | ```shell 17 | cargo run --release --config 'target."cfg(all())".runner="sudo -E"' 18 | ``` 19 | 20 | Cargo build scripts are used to automatically build the eBPF correctly and include it in the 21 | program. 22 | 23 | ## Cross-compiling on macOS 24 | 25 | Cross compilation should work on both Intel and Apple Silicon Macs. 26 | 27 | ```shell 28 | CC=${ARCH}-linux-musl-gcc cargo build --package {{project-name}} --release \ 29 | --target=${ARCH}-unknown-linux-musl \ 30 | --config=target.${ARCH}-unknown-linux-musl.linker=\"${ARCH}-linux-musl-gcc\" 31 | ``` 32 | The cross-compiled program `target/${ARCH}-unknown-linux-musl/release/{{project-name}}` can be 33 | copied to a Linux server or VM and run there. 34 | 35 | ## License 36 | 37 | With the exception of eBPF code, {{project-name}} is distributed under the terms 38 | of either the [MIT license] or the [Apache License] (version 2.0), at your 39 | option. 40 | 41 | Unless you explicitly state otherwise, any contribution intentionally submitted 42 | for inclusion in this crate by you, as defined in the Apache-2.0 license, shall 43 | be dual licensed as above, without any additional terms or conditions. 44 | 45 | ### eBPF 46 | 47 | All eBPF code is distributed under either the terms of the 48 | [GNU General Public License, Version 2] or the [MIT license], at your 49 | option. 50 | 51 | Unless you explicitly state otherwise, any contribution intentionally submitted 52 | for inclusion in this project by you, as defined in the GPL-2 license, shall be 53 | dual licensed as above, without any additional terms or conditions. 54 | 55 | [Apache license]: LICENSE-APACHE 56 | [MIT license]: LICENSE-MIT 57 | [GNU General Public License, Version 2]: LICENSE-GPL2 58 | -------------------------------------------------------------------------------- /cargo-generate.toml: -------------------------------------------------------------------------------- 1 | [template] 2 | cargo_generate_version = ">=0.10.0" 3 | ignore = [".github", "test.sh"] 4 | 5 | [placeholders.program_type] 6 | type = "string" 7 | prompt = "Which type of eBPF program?" 8 | choices = [ 9 | "cgroup_skb", 10 | "cgroup_sockopt", 11 | "cgroup_sysctl", 12 | "classifier", 13 | "fentry", 14 | "fexit", 15 | "kprobe", 16 | "kretprobe", 17 | "lsm", 18 | "perf_event", 19 | "raw_tracepoint", 20 | "sk_msg", 21 | "sock_ops", 22 | "socket_filter", 23 | "tp_btf", 24 | "tracepoint", 25 | "uprobe", 26 | "uretprobe", 27 | "xdp", 28 | ] 29 | default = "xdp" 30 | 31 | [conditional.'program_type == "kprobe" || program_type == "kretprobe"'.placeholders.kprobe] 32 | type = "string" 33 | prompt = "Where to attach the (k|kret)probe? (e.g try_to_wake_up)" 34 | 35 | [conditional.'program_type == "fentry" || program_type == "fexit"'.placeholders.fn_name] 36 | type = "string" 37 | prompt = "Where to attach the f(entry|exit)? (e.g try_to_wake_up)" 38 | 39 | [conditional.'program_type == "uprobe" || program_type == "uretprobe"'.placeholders.uprobe_target] 40 | type = "string" 41 | prompt = "Target to attach the (u|uret)probe? (e.g libc)" 42 | 43 | [conditional.'program_type == "uprobe" || program_type == "uretprobe"'.placeholders.uprobe_fn_name] 44 | type = "string" 45 | prompt = "Function name to attach the (u|uret)probe? (e.g getaddrinfo)" 46 | 47 | [conditional.'program_type == "cgroup_skb" || program_type == "classifier"'.placeholders.direction] 48 | type = "string" 49 | prompt = "Attach direction?" 50 | choices = ["Egress", "Ingress"] 51 | 52 | [conditional.'program_type == "cgroup_sockopt"'.placeholders.sockopt_target] 53 | type = "string" 54 | prompt = "Which socket option?" 55 | choices = ["getsockopt", "setsockopt"] 56 | 57 | [conditional.'program_type == "sk_msg"'.placeholders.sock_map] 58 | type = "string" 59 | prompt = "Map Name (UPPER_CASE)?" 60 | regex = "^[A-Z_]+$" 61 | 62 | [conditional.'program_type == "tracepoint"'.placeholders.tracepoint_category] 63 | type = "string" 64 | prompt = "Which tracepoint category? (e.g sched, net etc...)" 65 | regex = "^[a-z_]+$" 66 | 67 | [conditional.'program_type == "tracepoint" || program_type == "tp_btf" || program_type == "raw_tracepoint"'.placeholders.tracepoint_name] 68 | type = "string" 69 | prompt = "Which tracepoint name? (e.g sched_switch, net_dev_queue)" 70 | regex = "^[a-z_]+$" 71 | 72 | [conditional.'program_type == "lsm"'.placeholders.lsm_hook] 73 | type = "string" 74 | prompt = "Which lsm hook? (e.g file_open, task_alloc) You can find a list of hooks in include/linux/lsm_hook_defs.h in the kernel source tree." 75 | regex = "^[a-z_]+$" 76 | 77 | [hooks] 78 | pre = ["pre-script.rhai"] 79 | -------------------------------------------------------------------------------- /pre-script.rhai: -------------------------------------------------------------------------------- 1 | let program_types_with_opts = ["classifier", "cgroup_skb", "cgroup_sockopt", "cgroup_sysctl", "sock_ops", "uprobe", "uretprobe", "xdp"]; 2 | variable::set("program_types_with_opts", program_types_with_opts); 3 | -------------------------------------------------------------------------------- /rustfmt.toml: -------------------------------------------------------------------------------- 1 | group_imports = "StdExternalCrate" 2 | imports_granularity = "Crate" 3 | reorder_imports = true 4 | unstable_features = true 5 | -------------------------------------------------------------------------------- /test.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | set -eux 4 | 5 | TEMPLATE_DIR=$1 6 | if [ -z "${TEMPLATE_DIR}" ]; then 7 | echo "template dir required" 8 | exit 1 9 | fi 10 | PROG_TYPE=$2 11 | if [ -z "${PROG_TYPE}" ]; then 12 | echo "program type required" 13 | exit 1 14 | fi 15 | CRATE_NAME=aya-test-crate 16 | 17 | case ${PROG_TYPE} in 18 | "cgroup_sockopt") 19 | ADDITIONAL_ARGS=(-d sockopt_target=getsockopt) 20 | ;; 21 | "classifier" | "cgroup_skb") 22 | ADDITIONAL_ARGS=(-d direction=Ingress) 23 | ;; 24 | "fentry" | "fexit") 25 | ADDITIONAL_ARGS=(-d fn_name=try_to_wake_up) 26 | ;; 27 | "kprobe" | "kretprobe") 28 | ADDITIONAL_ARGS=(-d kprobe=do_unlinkat) 29 | ;; 30 | "lsm") 31 | ADDITIONAL_ARGS=(-d lsm_hook=file_open) 32 | ;; 33 | "raw_tracepoint") 34 | ADDITIONAL_ARGS=(-d tracepoint_name=sys_enter) 35 | ;; 36 | "sk_msg") 37 | ADDITIONAL_ARGS=(-d sock_map=SOCK_MAP) 38 | ;; 39 | "tp_btf") 40 | ADDITIONAL_ARGS=(-d tracepoint_name=net_dev_queue) 41 | ;; 42 | "tracepoint") 43 | ADDITIONAL_ARGS=(-d tracepoint_category=net -d tracepoint_name=net_dev_queue) 44 | ;; 45 | "uprobe" | "uretprobe") 46 | ADDITIONAL_ARGS=(-d uprobe_target=/proc/self/exe -d uprobe_fn_name=main) 47 | ;; 48 | *) 49 | ADDITIONAL_ARGS=() 50 | ;; 51 | esac 52 | 53 | TMP_DIR=$(mktemp -d) 54 | clean_up() { 55 | # shellcheck disable=SC2317 56 | rm -rf "${TMP_DIR}" 57 | } 58 | trap clean_up EXIT 59 | 60 | pushd "${TMP_DIR}" 61 | cargo generate --path "${TEMPLATE_DIR}" -n "${CRATE_NAME}" -d program_type="${PROG_TYPE}" "${ADDITIONAL_ARGS[@]}" 62 | pushd "${CRATE_NAME}" 63 | 64 | OS=$(uname) 65 | case $OS in 66 | "Darwin") 67 | ARCH=$(uname -m) 68 | if [[ "$ARCH" == "arm64" ]]; then 69 | ARCH="aarch64" 70 | fi 71 | TARGET=${ARCH}-unknown-linux-musl 72 | CC=${ARCH}-linux-musl-gcc cargo build --package "${CRATE_NAME}" --release \ 73 | --target="${TARGET}" \ 74 | --config=target."${TARGET}".linker=\""${ARCH}"-linux-musl-gcc\" 75 | ;; 76 | "Linux") 77 | cargo +nightly fmt --all -- --check 78 | cargo build --package "${CRATE_NAME}" 79 | cargo build --package "${CRATE_NAME}" --release 80 | # We cannot run clippy over the whole workspace at once due to feature unification. Since both 81 | # ${CRATE_NAME} and ${CRATE_NAME}-ebpf depend on ${CRATE_NAME}-common and ${CRATE_NAME} activates 82 | # ${CRATE_NAME}-common's aya dependency, we end up trying to compile the panic handler twice: once 83 | # from the bpf program, and again from std via aya. 84 | # 85 | # `-C panic=abort` because "unwinding panics are not supported without std"; 86 | # integration-ebpf contains `#[no_std]` binaries. 87 | # 88 | # `-Zpanic_abort_tests` because "building tests with panic=abort is not supported without 89 | # `-Zpanic_abort_tests`"; Cargo does this automatically when panic=abort is set via profile 90 | # but we want to preserve unwinding at runtime - here we are just running clippy so we don't 91 | # care about unwinding behavior. 92 | # 93 | # `+nightly` because "the option `Z` is only accepted on the nightly compiler". 94 | cargo +nightly clippy --exclude "${CRATE_NAME}-ebpf" --all-targets --workspace -- --deny warnings 95 | cargo +nightly clippy --package "${CRATE_NAME}-ebpf" --all-targets -- --deny warnings -C panic=abort -Zpanic_abort_tests 96 | 97 | expect < u32 { 10 | match try_{{crate_name}}(ctx) { 11 | Ok(ret) => ret, 12 | Err(ret) => ret, 13 | } 14 | } 15 | 16 | fn try_{{crate_name}}(ctx: ProbeContext) -> Result { 17 | info!(&ctx, "kprobe called"); 18 | Ok(0) 19 | } 20 | {%- when "kretprobe" %} 21 | use aya_ebpf::{macros::kretprobe, programs::RetProbeContext}; 22 | use aya_log_ebpf::info; 23 | 24 | #[kretprobe] 25 | pub fn {{crate_name}}(ctx: RetProbeContext) -> u32 { 26 | match try_{{crate_name}}(ctx) { 27 | Ok(ret) => ret, 28 | Err(ret) => ret, 29 | } 30 | } 31 | 32 | fn try_{{crate_name}}(ctx: RetProbeContext) -> Result { 33 | info!(&ctx, "kretprobe called"); 34 | Ok(0) 35 | } 36 | {%- when "fentry" %} 37 | use aya_ebpf::{macros::fentry, programs::FEntryContext}; 38 | use aya_log_ebpf::info; 39 | 40 | #[fentry(function = "{{fn_name}}")] 41 | pub fn {{crate_name}}(ctx: FEntryContext) -> u32 { 42 | match try_{{crate_name}}(ctx) { 43 | Ok(ret) => ret, 44 | Err(ret) => ret, 45 | } 46 | } 47 | 48 | fn try_{{crate_name}}(ctx: FEntryContext) -> Result { 49 | info!(&ctx, "function {{fn_name}} called"); 50 | Ok(0) 51 | } 52 | {%- when "fexit" %} 53 | use aya_ebpf::{macros::fexit, programs::FExitContext}; 54 | use aya_log_ebpf::info; 55 | 56 | #[fexit(function = "{{fn_name}}")] 57 | pub fn {{crate_name}}(ctx: FExitContext) -> u32 { 58 | match try_{{crate_name}}(ctx) { 59 | Ok(ret) => ret, 60 | Err(ret) => ret, 61 | } 62 | } 63 | 64 | fn try_{{crate_name}}(ctx: FExitContext) -> Result { 65 | info!(&ctx, "function {{fn_name}} called"); 66 | Ok(0) 67 | } 68 | {%- when "uprobe" %} 69 | use aya_ebpf::{macros::uprobe, programs::ProbeContext}; 70 | use aya_log_ebpf::info; 71 | 72 | #[uprobe] 73 | pub fn {{crate_name}}(ctx: ProbeContext) -> u32 { 74 | match try_{{crate_name}}(ctx) { 75 | Ok(ret) => ret, 76 | Err(ret) => ret, 77 | } 78 | } 79 | 80 | fn try_{{crate_name}}(ctx: ProbeContext) -> Result { 81 | info!(&ctx, "function {{uprobe_fn_name}} called by {{uprobe_target}}"); 82 | Ok(0) 83 | } 84 | {%- when "uretprobe" %} 85 | use aya_ebpf::{macros::uretprobe, programs::RetProbeContext}; 86 | use aya_log_ebpf::info; 87 | 88 | #[uretprobe] 89 | pub fn {{crate_name}}(ctx: RetProbeContext) -> u32 { 90 | match try_{{crate_name}}(ctx) { 91 | Ok(ret) => ret, 92 | Err(ret) => ret, 93 | } 94 | } 95 | 96 | fn try_{{crate_name}}(ctx: RetProbeContext) -> Result { 97 | info!(&ctx, "function {{uprobe_fn_name}} called by {{uprobe_target}}"); 98 | Ok(0) 99 | } 100 | {%- when "sock_ops" %} 101 | use aya_ebpf::{macros::sock_ops, programs::SockOpsContext}; 102 | use aya_log_ebpf::info; 103 | 104 | #[sock_ops] 105 | pub fn {{crate_name}}(ctx: SockOpsContext) -> u32 { 106 | match try_{{crate_name}}(ctx) { 107 | Ok(ret) => ret, 108 | Err(ret) => ret, 109 | } 110 | } 111 | 112 | fn try_{{crate_name}}(ctx: SockOpsContext) -> Result { 113 | info!(&ctx, "received TCP connection"); 114 | Ok(0) 115 | } 116 | {%- when "sk_msg" %} 117 | use aya_ebpf::{ 118 | macros::{map, sk_msg}, 119 | maps::SockHash, 120 | programs::SkMsgContext, 121 | }; 122 | use aya_log_ebpf::info; 123 | use {{crate_name}}_common::SockKey; 124 | 125 | #[map] 126 | static {{sock_map}}: SockHash = SockHash::::with_max_entries(1024, 0); 127 | 128 | #[sk_msg] 129 | pub fn {{crate_name}}(ctx: SkMsgContext) -> u32 { 130 | match try_{{crate_name}}(ctx) { 131 | Ok(ret) => ret, 132 | Err(ret) => ret, 133 | } 134 | } 135 | 136 | fn try_{{crate_name}}(ctx: SkMsgContext) -> Result { 137 | info!(&ctx, "received a message on the socket"); 138 | Ok(0) 139 | } 140 | {%- when "xdp" %} 141 | use aya_ebpf::{bindings::xdp_action, macros::xdp, programs::XdpContext}; 142 | use aya_log_ebpf::info; 143 | 144 | #[xdp] 145 | pub fn {{crate_name}}(ctx: XdpContext) -> u32 { 146 | match try_{{crate_name}}(ctx) { 147 | Ok(ret) => ret, 148 | Err(_) => xdp_action::XDP_ABORTED, 149 | } 150 | } 151 | 152 | fn try_{{crate_name}}(ctx: XdpContext) -> Result { 153 | info!(&ctx, "received a packet"); 154 | Ok(xdp_action::XDP_PASS) 155 | } 156 | {%- when "classifier" %} 157 | use aya_ebpf::{bindings::TC_ACT_PIPE, macros::classifier, programs::TcContext}; 158 | use aya_log_ebpf::info; 159 | 160 | #[classifier] 161 | pub fn {{crate_name}}(ctx: TcContext) -> i32 { 162 | match try_{{crate_name}}(ctx) { 163 | Ok(ret) => ret, 164 | Err(ret) => ret, 165 | } 166 | } 167 | 168 | fn try_{{crate_name}}(ctx: TcContext) -> Result { 169 | info!(&ctx, "received a packet"); 170 | Ok(TC_ACT_PIPE) 171 | } 172 | {%- when "cgroup_skb" %} 173 | use aya_ebpf::{macros::cgroup_skb, programs::SkBuffContext}; 174 | use aya_log_ebpf::info; 175 | 176 | #[cgroup_skb] 177 | pub fn {{crate_name}}(ctx: SkBuffContext) -> i32 { 178 | match try_{{crate_name}}(ctx) { 179 | Ok(ret) => ret, 180 | Err(ret) => ret, 181 | } 182 | } 183 | 184 | fn try_{{crate_name}}(ctx: SkBuffContext) -> Result { 185 | info!(&ctx, "received a packet"); 186 | Ok(0) 187 | } 188 | {%- when "tracepoint" %} 189 | use aya_ebpf::{macros::tracepoint, programs::TracePointContext}; 190 | use aya_log_ebpf::info; 191 | 192 | #[tracepoint] 193 | pub fn {{crate_name}}(ctx: TracePointContext) -> u32 { 194 | match try_{{crate_name}}(ctx) { 195 | Ok(ret) => ret, 196 | Err(ret) => ret, 197 | } 198 | } 199 | 200 | fn try_{{crate_name}}(ctx: TracePointContext) -> Result { 201 | info!(&ctx, "tracepoint {{tracepoint_name}} called"); 202 | Ok(0) 203 | } 204 | {%- when "lsm" %} 205 | use aya_ebpf::{macros::lsm, programs::LsmContext}; 206 | use aya_log_ebpf::info; 207 | 208 | #[lsm(hook = "{{lsm_hook}}")] 209 | pub fn {{lsm_hook}}(ctx: LsmContext) -> i32 { 210 | match try_{{lsm_hook}}(ctx) { 211 | Ok(ret) => ret, 212 | Err(ret) => ret, 213 | } 214 | } 215 | 216 | fn try_{{lsm_hook}}(ctx: LsmContext) -> Result { 217 | info!(&ctx, "lsm hook {{lsm_hook}} called"); 218 | Ok(0) 219 | } 220 | {%- when "tp_btf" %} 221 | use aya_ebpf::{macros::btf_tracepoint, programs::BtfTracePointContext}; 222 | use aya_log_ebpf::info; 223 | 224 | #[btf_tracepoint(function = "{{tracepoint_name}}")] 225 | pub fn {{tracepoint_name}}(ctx: BtfTracePointContext) -> i32 { 226 | match try_{{tracepoint_name}}(ctx) { 227 | Ok(ret) => ret, 228 | Err(ret) => ret, 229 | } 230 | } 231 | 232 | fn try_{{tracepoint_name}}(ctx: BtfTracePointContext) -> Result { 233 | info!(&ctx, "tracepoint {{tracepoint_name}} called"); 234 | Ok(0) 235 | } 236 | {%- when "socket_filter" %} 237 | use aya_ebpf::{macros::socket_filter, programs::SkBuffContext}; 238 | 239 | #[socket_filter] 240 | pub fn {{crate_name}}(_ctx: SkBuffContext) -> i64 { 241 | 0 242 | } 243 | {%- when "cgroup_sysctl" %} 244 | use aya_ebpf::{macros::cgroup_sysctl, programs::SysctlContext}; 245 | use aya_log_ebpf::info; 246 | 247 | #[cgroup_sysctl] 248 | pub fn {{crate_name}}(ctx: SysctlContext) -> i32 { 249 | match try_{{crate_name}}(ctx) { 250 | Ok(ret) => ret, 251 | Err(ret) => ret, 252 | } 253 | } 254 | 255 | fn try_{{crate_name}}(ctx: SysctlContext) -> Result { 256 | info!(&ctx, "sysctl operation called"); 257 | Ok(0) 258 | } 259 | {%- when "cgroup_sockopt" %} 260 | use aya_ebpf::{macros::cgroup_sockopt, programs::SockoptContext}; 261 | use aya_log_ebpf::info; 262 | 263 | #[cgroup_sockopt({{sockopt_target}})] 264 | pub fn {{crate_name}}(ctx: SockoptContext) -> i32 { 265 | match try_{{crate_name}}(ctx) { 266 | Ok(ret) => ret, 267 | Err(ret) => ret, 268 | } 269 | } 270 | 271 | fn try_{{crate_name}}(ctx: SockoptContext) -> Result { 272 | info!(&ctx, "{{sockopt_target}} called"); 273 | Ok(0) 274 | } 275 | {%- when "raw_tracepoint" %} 276 | use aya_ebpf::{macros::raw_tracepoint, programs::RawTracePointContext}; 277 | use aya_log_ebpf::info; 278 | 279 | #[raw_tracepoint(tracepoint = "{{tracepoint_name}}")] 280 | pub fn {{crate_name}}(ctx: RawTracePointContext) -> i32 { 281 | match try_{{crate_name}}(ctx) { 282 | Ok(ret) => ret, 283 | Err(ret) => ret, 284 | } 285 | } 286 | 287 | fn try_{{crate_name}}(ctx: RawTracePointContext) -> Result { 288 | info!(&ctx, "tracepoint {{tracepoint_name}} called"); 289 | Ok(0) 290 | } 291 | {%- when "perf_event" %} 292 | use aya_ebpf::{ 293 | helpers::bpf_get_smp_processor_id, macros::perf_event, programs::PerfEventContext, EbpfContext, 294 | }; 295 | use aya_log_ebpf::info; 296 | 297 | #[perf_event] 298 | pub fn {{crate_name}}(ctx: PerfEventContext) -> u32 { 299 | match try_{{crate_name}}(ctx) { 300 | Ok(ret) => ret, 301 | Err(ret) => ret, 302 | } 303 | } 304 | 305 | fn try_{{crate_name}}(ctx: PerfEventContext) -> Result { 306 | let cpu = unsafe { bpf_get_smp_processor_id() }; 307 | match ctx.pid() { 308 | 0 => info!( 309 | &ctx, 310 | "perf_event 'perftest' triggered on CPU {}, running a kernel task", cpu 311 | ), 312 | pid => info!( 313 | &ctx, 314 | "perf_event 'perftest' triggered on CPU {}, running PID {}", cpu, pid 315 | ), 316 | } 317 | 318 | Ok(0) 319 | } 320 | {%- endcase %} 321 | 322 | #[cfg(not(test))] 323 | #[panic_handler] 324 | fn panic(_info: &core::panic::PanicInfo) -> ! { 325 | loop {} 326 | } 327 | 328 | #[link_section = "license"] 329 | #[no_mangle] 330 | static LICENSE: [u8; 13] = *b"Dual MIT/GPL\0"; 331 | -------------------------------------------------------------------------------- /{{project-name}}/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "{{project-name}}" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | license.workspace = true 7 | 8 | [dependencies] 9 | {{project-name}}-common = { path = "../{{project-name}}-common", features = ["user"] } 10 | 11 | anyhow = { workspace = true, default-features = true } 12 | aya = { workspace = true } 13 | aya-log = { workspace = true } 14 | env_logger = { workspace = true } 15 | libc = { workspace = true } 16 | log = { workspace = true } 17 | tokio = { workspace = true, features = [ 18 | "macros", 19 | "rt", 20 | "rt-multi-thread", 21 | "net", 22 | "signal", 23 | ] } 24 | {% if program_types_with_opts contains program_type -%} 25 | clap = { workspace = true, features = ["derive"] } 26 | {% endif -%} 27 | 28 | [build-dependencies] 29 | anyhow = { workspace = true } 30 | aya-build = { workspace = true } 31 | # TODO(https://github.com/rust-lang/cargo/issues/12375): this should be an artifact dependency, but 32 | # it's not possible to tell cargo to use `-Z build-std` to build it. We cargo-in-cargo in the build 33 | # script to build this, but we want to teach cargo about the dependecy so that cache invalidation 34 | # works properly. 35 | # 36 | # Note also that https://github.com/rust-lang/cargo/issues/10593 occurs when `target = ...` is added 37 | # to an artifact dependency; it seems possible to work around that by setting `resolver = "1"` in 38 | # Cargo.toml in the workspace root. 39 | # 40 | # Finally note that *any* usage of `artifact = ...` in *any* Cargo.toml in the workspace breaks 41 | # workflows with stable cargo; stable cargo outright refuses to load manifests that use unstable 42 | # features. 43 | {{project-name}}-ebpf = { path = "../{{project-name}}-ebpf" } 44 | 45 | [[bin]] 46 | name = "{{project-name}}" 47 | path = "src/main.rs" 48 | -------------------------------------------------------------------------------- /{{project-name}}/build.rs: -------------------------------------------------------------------------------- 1 | use anyhow::{anyhow, Context as _}; 2 | use aya_build::cargo_metadata; 3 | 4 | fn main() -> anyhow::Result<()> { 5 | let cargo_metadata::Metadata { packages, .. } = cargo_metadata::MetadataCommand::new() 6 | .no_deps() 7 | .exec() 8 | .context("MetadataCommand::exec")?; 9 | let ebpf_package = packages 10 | .into_iter() 11 | .find(|cargo_metadata::Package { name, .. }| name == "{{project-name}}-ebpf") 12 | .ok_or_else(|| anyhow!("{{project-name}}-ebpf package not found"))?; 13 | aya_build::build_ebpf([ebpf_package]) 14 | } 15 | -------------------------------------------------------------------------------- /{{project-name}}/src/main.rs: -------------------------------------------------------------------------------- 1 | {%- case program_type -%} 2 | {%- when "kprobe", "kretprobe" -%} 3 | use aya::programs::KProbe; 4 | {%- when "fentry" -%} 5 | use anyhow::Context as _; 6 | use aya::{programs::FEntry, Btf}; 7 | {%- when "fexit" -%} 8 | use anyhow::Context as _; 9 | use aya::{programs::FExit, Btf}; 10 | {%- when "uprobe", "uretprobe" -%} 11 | use aya::programs::UProbe; 12 | {%- when "sock_ops" -%} 13 | use anyhow::Context as _; 14 | use aya::programs::{links::CgroupAttachMode, SockOps}; 15 | {%- when "sk_msg" -%} 16 | use aya::{maps::SockHash, programs::SkMsg}; 17 | use {{crate_name}}_common::SockKey; 18 | {%- when "xdp" -%} 19 | use anyhow::Context as _; 20 | use aya::programs::{Xdp, XdpFlags}; 21 | {%- when "classifier" -%} 22 | use aya::programs::{tc, SchedClassifier, TcAttachType}; 23 | {%- when "cgroup_skb" -%} 24 | use anyhow::Context as _; 25 | use aya::programs::{links::CgroupAttachMode, CgroupSkb, CgroupSkbAttachType}; 26 | {%- when "cgroup_sysctl" -%} 27 | use anyhow::Context as _; 28 | use aya::programs::{links::CgroupAttachMode, CgroupSysctl}; 29 | {%- when "cgroup_sockopt" -%} 30 | use anyhow::Context as _; 31 | use aya::programs::{links::CgroupAttachMode, CgroupSockopt}; 32 | {%- when "tracepoint" -%} 33 | use aya::programs::TracePoint; 34 | {%- when "lsm" -%} 35 | use aya::{programs::Lsm, Btf}; 36 | {%- when "perf_event" -%} 37 | use aya::{ 38 | programs::{perf_event, PerfEvent}, 39 | util::online_cpus, 40 | }; 41 | {%- when "tp_btf" -%} 42 | use aya::{programs::BtfTracePoint, Btf}; 43 | {%- when "socket_filter" -%} 44 | use aya::programs::SocketFilter; 45 | {%- when "raw_tracepoint" -%} 46 | use aya::programs::RawTracePoint; 47 | {%- endcase %} 48 | {% if program_types_with_opts contains program_type -%} 49 | use clap::Parser; 50 | {% endif -%} 51 | 52 | #[rustfmt::skip] 53 | use log::{debug, warn}; 54 | use tokio::signal; 55 | 56 | {% if program_types_with_opts contains program_type -%} 57 | #[derive(Debug, Parser)] 58 | struct Opt { 59 | {%- case program_type -%} 60 | {%- when "xdp", "classifier" %} 61 | #[clap(short, long, default_value = "eth0")] 62 | iface: String, 63 | {%- when "sock_ops", "cgroup_skb", "cgroup_sysctl", "cgroup_sockopt" %} 64 | #[clap(short, long, default_value = "/sys/fs/cgroup")] 65 | cgroup_path: std::path::PathBuf, 66 | {%- when "uprobe", "uretprobe" %} 67 | #[clap(short, long)] 68 | pid: Option, 69 | {%- endcase %} 70 | } 71 | 72 | {% endif -%} 73 | #[tokio::main] 74 | async fn main() -> anyhow::Result<()> { 75 | {%- if program_types_with_opts contains program_type %} 76 | let opt = Opt::parse(); 77 | {% endif %} 78 | env_logger::init(); 79 | 80 | // Bump the memlock rlimit. This is needed for older kernels that don't use the 81 | // new memcg based accounting, see https://lwn.net/Articles/837122/ 82 | let rlim = libc::rlimit { 83 | rlim_cur: libc::RLIM_INFINITY, 84 | rlim_max: libc::RLIM_INFINITY, 85 | }; 86 | let ret = unsafe { libc::setrlimit(libc::RLIMIT_MEMLOCK, &rlim) }; 87 | if ret != 0 { 88 | debug!("remove limit on locked memory failed, ret is: {ret}"); 89 | } 90 | 91 | // This will include your eBPF object file as raw bytes at compile-time and load it at 92 | // runtime. This approach is recommended for most real-world use cases. If you would 93 | // like to specify the eBPF program at runtime rather than at compile-time, you can 94 | // reach for `Bpf::load_file` instead. 95 | let mut ebpf = aya::Ebpf::load(aya::include_bytes_aligned!(concat!( 96 | env!("OUT_DIR"), 97 | "/{{project-name}}" 98 | )))?; 99 | if let Err(e) = aya_log::EbpfLogger::init(&mut ebpf) { 100 | // This can happen if you remove all log statements from your eBPF program. 101 | warn!("failed to initialize eBPF logger: {e}"); 102 | } 103 | {%- case program_type -%} 104 | {%- when "kprobe", "kretprobe" %} 105 | let program: &mut KProbe = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 106 | program.load()?; 107 | program.attach("{{kprobe}}", 0)?; 108 | {%- when "fentry" %} 109 | let btf = Btf::from_sys_fs().context("BTF from sysfs")?; 110 | let program: &mut FEntry = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 111 | program.load("{{fn_name}}", &btf)?; 112 | program.attach()?; 113 | {%- when "fexit" %} 114 | let btf = Btf::from_sys_fs().context("BTF from sysfs")?; 115 | let program: &mut FExit = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 116 | program.load("{{fn_name}}", &btf)?; 117 | program.attach()?; 118 | {%- when "uprobe", "uretprobe" %} 119 | let Opt { pid } = opt; 120 | let program: &mut UProbe = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 121 | program.load()?; 122 | program.attach(Some("{{uprobe_fn_name}}"), 0, "{{uprobe_target}}", pid)?; 123 | {%- when "sock_ops", "cgroup_skb", "cgroup_sysctl", "cgroup_sockopt" %} 124 | let Opt { cgroup_path } = opt; 125 | let cgroup = 126 | std::fs::File::open(&cgroup_path).with_context(|| format!("{}", cgroup_path.display()))?; 127 | {%- if program_type == "sock_ops" %} 128 | let program: &mut SockOps = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 129 | program.load()?; 130 | program.attach(cgroup, CgroupAttachMode::default())?; 131 | {%- elsif program_type == "cgroup_skb" %} 132 | let program: &mut CgroupSkb = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 133 | program.load()?; 134 | program.attach( 135 | cgroup, 136 | CgroupSkbAttachType::{{direction}}, 137 | CgroupAttachMode::default(), 138 | )?; 139 | {%- elsif program_type == "cgroup_sysctl" %} 140 | let program: &mut CgroupSysctl = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 141 | program.load()?; 142 | program.attach(cgroup, CgroupAttachMode::default())?; 143 | {%- elsif program_type == "cgroup_sockopt" %} 144 | let program: &mut CgroupSockopt = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 145 | program.load()?; 146 | program.attach(cgroup, CgroupAttachMode::default())?; 147 | {%- endif -%} 148 | {%- when "sk_msg" %} 149 | let sock_map: SockHash<_, SockKey> = ebpf.map("{{sock_map}}").unwrap().try_into()?; 150 | let map_fd = sock_map.fd().try_clone()?; 151 | let prog: &mut SkMsg = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 152 | prog.load()?; 153 | prog.attach(&map_fd)?; 154 | // insert sockets to the map using sock_map.insert here, or from a sock_ops program 155 | {%- when "xdp" %} 156 | let Opt { iface } = opt; 157 | let program: &mut Xdp = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 158 | program.load()?; 159 | program.attach(&iface, XdpFlags::default()) 160 | .context("failed to attach the XDP program with default flags - try changing XdpFlags::default() to XdpFlags::SKB_MODE")?; 161 | {%- when "classifier" %} 162 | let Opt { iface } = opt; 163 | // error adding clsact to the interface if it is already added is harmless 164 | // the full cleanup can be done with 'sudo tc qdisc del dev eth0 clsact'. 165 | let _ = tc::qdisc_add_clsact(&iface); 166 | let program: &mut SchedClassifier = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 167 | program.load()?; 168 | program.attach(&iface, TcAttachType::{{direction}})?; 169 | {%- when "tracepoint" %} 170 | let program: &mut TracePoint = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 171 | program.load()?; 172 | program.attach("{{tracepoint_category}}", "{{tracepoint_name}}")?; 173 | {%- when "lsm" %} 174 | let btf = Btf::from_sys_fs()?; 175 | let program: &mut Lsm = ebpf.program_mut("{{lsm_hook}}").unwrap().try_into()?; 176 | program.load("{{lsm_hook}}", &btf)?; 177 | program.attach()?; 178 | {%- when "tp_btf" %} 179 | let btf = Btf::from_sys_fs()?; 180 | let program: &mut BtfTracePoint = ebpf.program_mut("{{tracepoint_name}}").unwrap().try_into()?; 181 | program.load("{{tracepoint_name}}", &btf)?; 182 | program.attach()?; 183 | {%- when "socket_filter" %} 184 | let listener = std::net::TcpListener::bind("localhost:0")?; 185 | let prog: &mut SocketFilter = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 186 | prog.load()?; 187 | prog.attach(&listener)?; 188 | {%- when "perf_event" %} 189 | // This will raise scheduled events on each CPU at 1 HZ, triggered by the kernel based 190 | // on clock ticks. 191 | let program: &mut PerfEvent = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 192 | program.load()?; 193 | for cpu in online_cpus().map_err(|(_, error)| error)? { 194 | program.attach( 195 | perf_event::PerfTypeId::Software, 196 | perf_event::perf_sw_ids::PERF_COUNT_SW_CPU_CLOCK as u64, 197 | perf_event::PerfEventScope::AllProcessesOneCpu { cpu }, 198 | perf_event::SamplePolicy::Frequency(1), 199 | true, 200 | )?; 201 | } 202 | {%- when "raw_tracepoint" %} 203 | let program: &mut RawTracePoint = ebpf.program_mut("{{crate_name}}").unwrap().try_into()?; 204 | program.load()?; 205 | program.attach("{{tracepoint_name}}")?; 206 | {%- endcase %} 207 | 208 | let ctrl_c = signal::ctrl_c(); 209 | println!("Waiting for Ctrl-C..."); 210 | ctrl_c.await?; 211 | println!("Exiting..."); 212 | 213 | Ok(()) 214 | } 215 | --------------------------------------------------------------------------------