├── .github
└── workflows
│ ├── build-release-binaries.yaml
│ └── go.yml
├── .gitignore
├── LICENSE
├── README.md
├── bin
├── emperium-aarch64
└── emperium-x86_64
├── ctf.yaml
└── eBPF
├── header
└── vmlinux.h
├── map
├── go.mod
├── go.sum
└── main.go
├── redirect
├── ebpf
│ └── redirect.c
├── go.mod
├── go.sum
└── main.go
└── response
├── ebpf
└── response.c
├── go.mod
├── go.sum
└── main.go
/.github/workflows/build-release-binaries.yaml:
--------------------------------------------------------------------------------
1 | name: goreleaser
2 |
3 | on:
4 | pull_request:
5 | push:
6 | # run only against tags
7 | tags:
8 | - "*"
9 |
10 | permissions:
11 | contents: write
12 | # packages: write
13 | # issues: write
14 |
15 | jobs:
16 | goreleaser:
17 | runs-on: ubuntu-latest
18 | steps:
19 | - name: Checkout
20 | uses: actions/checkout@v4
21 | with:
22 | fetch-depth: 0
23 | - name: Set up Go
24 | uses: actions/setup-go@v5
25 | with:
26 | go-version: stable
27 | # More assembly might be required: Docker logins, GPG, etc.
28 | # It all depends on your needs.
29 | - name: Run GoReleaser
30 | uses: goreleaser/goreleaser-action@v6
31 | with:
32 | # either 'goreleaser' (default) or 'goreleaser-pro'
33 | distribution: goreleaser
34 | # 'latest', 'nightly', or a semver
35 | version: "~> v2"
36 | args: release --clean
37 | env:
38 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
--------------------------------------------------------------------------------
/.github/workflows/go.yml:
--------------------------------------------------------------------------------
1 | # This workflow will build a golang project
2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-go
3 |
4 | name: Go
5 |
6 | on:
7 | push:
8 | branches: [ "main" ]
9 | pull_request:
10 | branches: [ "main" ]
11 |
12 | jobs:
13 |
14 | build:
15 | runs-on: ubuntu-latest
16 | steps:
17 | - uses: actions/checkout@v4
18 |
19 | - name: Set up Go
20 | uses: actions/setup-go@v4
21 | with:
22 | go-version: '1.21.3'
23 |
24 | - name: Build
25 | run: cd emperium; go build
26 |
27 | - name: Release
28 | uses: softprops/action-gh-release@v2
29 | with:
30 | files: ./emperium/emperium
31 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | emperium/emperium
2 | eBPF/response/response
3 | emperium/emperium
4 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "[]"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright [yyyy] [name of copyright owner]
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # eBPF Summit 2024 Capture the Flag ⛳️🐝
2 |
3 | Welcome to the eBPF 2024 Summit CTF, this year the task will involve a number of challenges around various eBPF technologies. Some of the challenges will require use of CLI tools such as `bpftool` and some will require fixing or completing some partial code in order to complete the challenge.
4 |
5 | ## Getting help and solving the CTF
6 |
7 | Please register at the [eBPF slack](https://slack.cilium.io) and join the `#ebpf-summit` & `#ebpf-summit-ctf-spoilers` channels! Here you will find help and clues, and also a place to submit your answers once you've completed the CTF!.
8 |
9 | ## Getting the CTF up and running !
10 |
11 | The CTF makes use of the [lima](https://github.com/lima-vm/lima) project to simplify the process of creating a virtual machine that will run the CTF. The virtual machine once created will contain:
12 |
13 | - CTF program
14 | - code-server (VS-CODE but accessed through a browser)
15 | - vim
16 | - a `~/ebpf` directory that is filled with the sample code for the challenges
17 |
18 | ## Create the CTF VM
19 | You will need to take the `ctf.yaml` in this repository and start it with `limactl`, this will build and start the virtual machine!
20 |
21 | `limactl start ctf.yaml`
22 |
23 | ## Accessing the VM
24 |
25 | You will need at least two shells in order to access both the `emperium` system and the underlying OS in order to interact with the Kernel and eBPF programs.
26 |
27 | ### First shell
28 |
29 | This will connect to the running system and start `emperium`.
30 |
31 | `limactl shell ctf sudo /tmp/emperium`
32 |
33 | ```
34 |
35 | ._,.
36 | "..-..pf.
37 | -L ..#'
38 | .+_L ."]#
39 | ,'j' .+.j' -'.__..,.,p.
40 | _~ #..<..0. .J-.''..._f.
41 | .7..#_.. _f. .....-..,'4'
42 | ;' ,#j. T' .. ..J....,'.j'
43 | .' .."^.,-0.,,,,yMMMMM,. ,-.J...+'.j@
44 | .'.'...' .yMMMMM0M@^='""g.. .'..J..".'.jH
45 | j' .'1' q'^)@@#"^".'"='BNg_...,]_)'...0-
46 | .T ...I. j" .'..+,_.'3#MMM0MggCBf....F.
47 | j/.+'.{..+ '^~'-^~~""""'"""?'"'''1'
48 | .... .y.} '.._-:'_...jf
49 | g-. .Lg' ..,..'-....,'.
50 | .'. .Y^ .....',].._f
51 | ......-f. .-,,.,.-:--&'
52 | .'...'..'_J'
53 | .~......'#' Tie Fighter Manufacturing
54 | '..,,.,_]' Security Systems
55 | .L..'..''.
56 | Data system> Initialising...
57 | Data system> Ready
58 | Security Status> Enabled
59 | Security Lock 1> [ ▮ ]
60 | Security Lock 2> [ ▮ ]
61 | Security Lock 3> [ ▮ ]
62 | ```
63 |
64 | ### Second shell
65 |
66 | The following line will connect through to the VM using SSH, it will also port forward from inside the VM (port 80) to port `8082` on your local machine. The reason for this is to allow the use of code-server to interact with the `eBPF` 🐝 code.
67 |
68 | `ssh -F $HOME/.lima/ctf/ssh.config -L "*:8082:0.0.0.0:80" lima-ctf`
69 |
70 | To start `code-server` within the VM run the command:
71 |
72 | `PASSWORD=password code-server --bind-addr=0.0.0.0 > /tmp/code.log &`.
73 |
74 | **Additionally**: You may find it makes things a little easier to install some plugins to make things easier, such as the `clangd` extension or the `golang` extension.
75 |
76 | ## Setting up the eBPF code
77 |
78 | All of the code lives within `~/eBPF` and is automatically created when you start the first shell, so if this is missing ensure you're following the instructions.
79 |
80 | ### Code-Server or Vim
81 |
82 | To make life as easy as possible we've packaged both Vim and Code-server for you to create and modify Go and eBPF code. To connect to code-server open a browser and point it to the IP address of the host where the `lima` VM is running (not the CTF VM IP, the IP of the hosting machine itself). Connecting to port `8082` will open code-server that will allow you to work inside the CTF VM. The CTF source code is in your home directory!
83 |
84 | ### Compiling the code
85 |
86 | In each of the folders in `~/eBPF` is some half completed eBPF 🐝 programs. Most of the programs will require running `go generate` in order to compile the C/eBPF source code first before you can run the main go binary. Additionally to run the go programs themselves the easiest approach is to either `go build` and run the resulting binary with `sudo` or the do `go run -exec sudo .`.
87 |
88 | ## The challenge !
89 |
90 | They are _everywhere_. This is a true infestation. Way worse than the rockmites you had to fight off to defend your giant bees, back in your days as a beekeeper. Worse, even, than the herd of mynocks you found in that asteroid field, when ambushing an Imperial transporter (which turned up to carry no sensitive information, but never mind, they freighted chocolates, and they're delicious). This time, they just won't stop coming. And they're big things, flying fast, with a terrible roar.
91 |
92 | These are TIE Fighters from the Empire. And they're after you.
93 |
94 | Jephen'Tsa is your name, and you've made life tough for the Empire. But this time, Imperials are the ones harassing your team. If they can't pin down the exact location of your Rebel base, they have a gross idea of the area where you're hiding, courtesy of your sworn enemy, the traitor Bajeroff Lake. Armadas of TIEs have been patrolling in the whole constellation, and every mission, every outing has been a pain. Sure, the Rebel Alliance has some of the best pilots in the galaxy, but for each fighter they strike down, five new ships come out of the factory. Your own vessel, the _Yellow Stripe_, is docked for repairs. This is untenable. If you could just stop enemy fighters from coming back...
95 |
96 | As it turns out, an opportunity came up this morning, thanks to the hard work of your friend and ally, Blue Hex. Her utility droid, IP-V6, just brought you to the control room, where Blue Hex explains how her spy network is getting close to disable the whole TIE fighter production lines, no less! She has established a hidden connection to the mainframe in the manufacturing facility, but disabling it requires accessing the core controls of the system, protected by **four** security locks. Oh wait, an alarm erupts! Some TIEs are nearby! Did they find your hideout at last? Blue Hex stops her briefing and jumps into her ship, imitated by the other pilots.
97 |
98 | But your own spacecraft is not ready, and for this time you're grounded. You should as well look into these security locks, to disable the factory. That would be quite an achievement... One more to add to your name? Sit down and relax. The Force is with you. You can do it. Let's start by sending IP-V6 fetch a few more of these delicious chocolates...
99 |
100 |
101 | ### Part 1 - unscramble the message
102 | A hacker from the Zenith system in the employ of the Rebellion managed to get a communication out, whilst the quality was poor technicians managed to enhance enough of the audio to understand that the hacker may have "got it the wrong way around" and that the bpftool might be the best way to fix it.
103 |
104 |
105 | First Clue
106 |
107 | `bpftool` can be used to list all of the maps
108 |
109 | Second Clue
110 |
111 | `bpftool` can dump the contents of a specific map identified by name or ID
112 |
113 | Final Clue
114 |
115 | `bpftool` can update the contents of the specific key/value within a map.
116 |
117 |
118 |
119 |
120 | ### Part 2 - complete the keycodes
121 | Our spies managed to extract one of the vital keycodes from the emperium key vaults, they unfortunately deleted the emperium map in the process. Whilst we now have this data `brRz3HVSVzC6RXrBC2Y7`, we're not sure if this will impact the running `emperium` system. 📂`eBPF/map` (or perhaps this can be done with `bpftool` 🤔)
122 |
123 |
124 | First Clue
125 |
126 | Partially completed code is one way to help you achieve this, you'll need to look at an existing map to understand the key/values
127 |
128 | Second Clue
129 |
130 | An `eBPF` map will only exist as long as a program or file has a reference too it, otherwise it will be garbage collected.
131 |
132 |
133 |
134 | ### Part 3 - get authenticated
135 | An archive taken from a stolen ship has revealed the third security lock is broken due to the authentication being pushed to the wrong port. One of the engineers has managed to put something together, but keeps muttering about "Endianness" and returning traffic. 📂`eBPF/redirect/`
136 |
137 |
138 | First Clue
139 |
140 | Is something generating network traffic on the `lo` interface?
141 |
142 | Second Clue
143 |
144 | In most cases, numbers are carried in network packets in [big-endian](https://en.wikipedia.org/wiki/Endianness#/media/File:32bit-Endianess.svg) byte order, which may differ from the host byte order on a particular machine. So often you may need to convert between host byte order and network byte order. There are bpf helper functions that will allow you to convert between the two.
145 |
146 |
147 | Third Clue
148 |
149 | Changing a destination port will effectively change where traffic is being sent to, although it may confuse the networking stack to suddenly receive a reply to a port that it wasn't expecting...
150 |
151 |
152 |
153 |
154 | ### Part 4 - access the mainframe
155 | A defector has provided most of the code that is needed in order to create a fake `emperium` mainframe, once up this will be able to **"acknowledge"** the `emperium` system. The specialist that wrote most of this was reassigned after breaking his keyboard about a "verifier"? 📂`eBPF/response/`
156 |
157 |
158 | First Clue
159 |
160 | You'll need to modify the partially-complete code so that it passes the eBPF Verifier
161 |
162 |
163 | Second Clue
164 |
165 | There are BPF helper functions for reading bytes out of the kernel's network packet data structure (a.k.a. `skb`) as well as for storing bytes in it.
166 |
167 |
168 |
169 | ## Additional
170 |
171 | You can also run the `/emperium` program locally (with root privileges) on a Linux machine if you don't want to use lima. It will attempt to write the source code to a `eBPF` folder so ensure one doesn't exist in the directory you run the `/emperium` program.
172 |
--------------------------------------------------------------------------------
/bin/emperium-aarch64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isovalent/eBPF-Summit-2024-CTF/700201b240c7858c389dcb6193991ea818511bdc/bin/emperium-aarch64
--------------------------------------------------------------------------------
/bin/emperium-x86_64:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/isovalent/eBPF-Summit-2024-CTF/700201b240c7858c389dcb6193991ea818511bdc/bin/emperium-x86_64
--------------------------------------------------------------------------------
/ctf.yaml:
--------------------------------------------------------------------------------
1 | # This template requires Lima v0.7.0 or later.
2 | images:
3 | # Try to use release-yyyyMMdd image if available. Note that release-yyyyMMdd will be removed after several months.
4 | - location: "https://cloud-images.ubuntu.com/releases/24.04/release-20240725/ubuntu-24.04-server-cloudimg-amd64.img"
5 | arch: "x86_64"
6 | digest: "sha256:d2377667ea95222330ca2287817403c85178dad397e9fed768a9b4aec79d2a7f"
7 | - location: "https://cloud-images.ubuntu.com/releases/24.04/release-20240725/ubuntu-24.04-server-cloudimg-arm64.img"
8 | arch: "aarch64"
9 | digest: "sha256:2c47dbf04477993ebcd921250b1aab8e582d2fdd03d7576b57d28b6aeeff1427"
10 | # Fallback to the latest release image.
11 | # Hint: run `limactl prune` to invalidate the cache
12 | - location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-amd64.img"
13 | arch: "x86_64"
14 | - location: "https://cloud-images.ubuntu.com/releases/24.04/release/ubuntu-24.04-server-cloudimg-arm64.img"
15 | arch: "aarch64"
16 |
17 | # containerd is managed by k3s, not by Lima, so the values are set to false here.
18 | containerd:
19 | system: false
20 | user: false
21 |
22 | ### In case you wish to mount your home directory
23 | # mounts:
24 | #- location: "~"
25 |
26 | provision:
27 | - mode: system
28 | script: |
29 | #!/bin/sh
30 | sudo apt-get update; sudo apt-get install -y linux-tools-$(uname -r) libbpf-dev clang vim golang-go git llvm
31 | sudo curl -L https://github.com/isovalent/eBPF-Summit-2024-CTF/raw/main/bin/emperium-$(uname -m) > /tmp/emperium && chmod +x /tmp/emperium
32 | - mode: user
33 | script: |
34 | #!/bin/sh
35 | curl -fsSL https://code-server.dev/install.sh | sh
36 | probes:
37 | - script: |
38 | #!/bin/bash
39 | message: |
40 | Welcome to the eBPF Summit 2024 !!
41 | ------
42 | In one terminal you can connect to your running instance with the command:
43 | limactl shell ctf sudo /tmp/emperium
44 |
45 | In another terminal connect with
46 | ssh -F $HOME/.lima/ctf/ssh.config -L "*:8082:0.0.0.0:80" lima-ctf
47 |
48 | Start code-server with:
49 | PASSWORD=password code-server --bind-addr=0.0.0.0 > /tmp/code.log &
50 | ------
51 |
--------------------------------------------------------------------------------
/eBPF/map/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/thebsdbox/eBPF-Summit-2024-CTF/eBPF/map
2 |
3 | go 1.21.3
4 |
5 | require github.com/cilium/ebpf v0.16.0
6 |
7 | require (
8 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 // indirect
9 | golang.org/x/sys v0.20.0 // indirect
10 | )
11 |
--------------------------------------------------------------------------------
/eBPF/map/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cilium/ebpf v0.16.0 h1:+BiEnHL6Z7lXnlGUsXQPPAE7+kenAd4ES8MQ5min0Ok=
2 | github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEngfwE=
3 | github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
4 | github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
5 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
6 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
7 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
8 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
9 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
10 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
11 | github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
12 | github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
13 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 h1:Jvc7gsqn21cJHCmAWx0LiimpP18LZmUxkT5Mp7EZ1mI=
14 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
15 | golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
16 | golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
17 |
--------------------------------------------------------------------------------
/eBPF/map/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | log "log/slog"
5 |
6 | "github.com/cilium/ebpf"
7 | "github.com/cilium/ebpf/rlimit"
8 | )
9 |
10 | func main() {
11 | // Allow the current process to lock memory for eBPF resources.
12 | if err := rlimit.RemoveMemlock(); err != nil {
13 | log.Error("rlimit")
14 | panic(err)
15 | }
16 | // Create our templatae map spec
17 | mapSpec := ebpf.MapSpec{
18 | Type: ebpf.Hash,
19 | KeySize: 1, // 4 bytes for u32
20 | ValueSize: 20,
21 | MaxEntries: 1, // We'll have 1 entry
22 | }
23 |
24 | // Lets create a map
25 | mapSpec.Name = ""
26 | mapSpec.Contents = []ebpf.MapKV{
27 | {Key: uint8(1), Value: []byte("")},
28 | }
29 | m, err := ebpf.NewMap(&mapSpec)
30 | if err != nil {
31 | log.Error("map create fail ")
32 | panic(err)
33 | }
34 | defer m.Close()
35 | //time.Sleep(time.Minute)
36 | }
37 |
--------------------------------------------------------------------------------
/eBPF/redirect/ebpf/redirect.c:
--------------------------------------------------------------------------------
1 | // +build ignore
2 |
3 | #include "../../header/vmlinux.h"
4 | #include
5 | #include
6 | #include
7 |
8 | #pragma pack(1)
9 | // TC Return codes
10 | #define TC_ACT_OK 0
11 | #define TC_ACT_SHOT 2
12 |
13 | #define ETH_P_IP 0x0800 /* Internet Protocol packet */
14 | #define ETH_HLEN 14 /*Ethernet Header Length */
15 | #define ETH_ALEN 6
16 |
17 | char __license[] SEC("license") = "GPL";
18 |
19 | static inline int redirect_tcp(struct __sk_buff *skb, bool ingress) {
20 | // Get pointers to the beginning and end
21 | void *data_end = (void *)(long)skb->data_end;
22 | void *data = (void *)(long)skb->data;
23 |
24 | // Point to ethernet header
25 | struct ethhdr *eth = data;
26 | __u16 h_proto;
27 | __u64 nh_off = 0;
28 | nh_off = sizeof(*eth);
29 |
30 | if (data + nh_off > data_end) {
31 | return TC_ACT_OK;
32 | }
33 |
34 | // Get protocol
35 | h_proto = eth->h_proto;
36 |
37 | // if it is IP continue
38 | if (h_proto == bpf_htons(ETH_P_IP)) {
39 | struct iphdr *iph = data + nh_off;
40 |
41 | // Get pointer to IP Header
42 | if ((void *)(iph + 1) > data_end) {
43 | return TC_ACT_OK;
44 | }
45 |
46 | // Check protocol inside IP packet
47 | if (iph->protocol != IPPROTO_TCP) {
48 | return TC_ACT_OK;
49 | }
50 | __u32 ip_hlen = 0;
51 |
52 | ip_hlen = iph->ihl << 2;
53 |
54 | if (ip_hlen < sizeof(*iph)) {
55 | return TC_ACT_OK;
56 | }
57 | struct iphdr ip;
58 | struct tcphdr tcp;
59 |
60 | if (0 != bpf_skb_load_bytes(skb, sizeof(struct ethhdr), &ip,
61 | sizeof(struct iphdr))) {
62 | bpf_printk("bpf_skb_load_bytes iph failed");
63 | return TC_ACT_OK;
64 | }
65 |
66 | if (0 != bpf_skb_load_bytes(skb, sizeof(struct ethhdr) + (ip.ihl << 2),
67 | &tcp, sizeof(struct tcphdr))) {
68 | bpf_printk("bpf_skb_load_bytes eth failed");
69 | return TC_ACT_OK;
70 | }
71 |
72 | // something doesn't seem right here
73 | __u16 source = tcp.source;
74 | __u16 dest = tcp.dest;
75 |
76 | // Print out any traffic we might be interested in
77 | if (source > 1024 && dest > 1024) {
78 | bpf_printk("ingress:%s source: %d -> destination %d",
79 | ingress ? "true" : "false", source, dest);
80 | }
81 |
82 | if (ingress) {
83 | if (dest == 2001) {
84 | tcp.dest = 2000;
85 | long ret =
86 | bpf_skb_store_bytes(skb, sizeof(struct ethhdr) + (ip.ihl << 2),
87 | &tcp, sizeof(tcp), BPF_F_RECOMPUTE_CSUM);
88 | if (ret != 0) {
89 | bpf_printk("Error writing bytes");
90 | }
91 | }
92 | } else {
93 | // something is missing here
94 | }
95 |
96 | // The Rebel engineer left some TCP dump output, might help, might be a read
97 | // herring
98 | /*
99 | 15:27:27.195146 IP (tos 0x0, ttl 64, id 64035, offset 0, flags [DF], proto
100 | TCP (6), length 60) 127.0.0.1.55590 > 127.0.0.1.2001: Flags [S], cksum
101 | 0xfe30 (incorrect -> 0xde8f), seq 1127217463, win 65495, options [mss
102 | 65495,sackOK,TS val 1342243858 ecr 0,nop,wscale 7], length 0 15:27:27.195160
103 | IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 40)
104 | 127.0.0.1.2001 > 127.0.0.1.55590: Flags [R.], cksum 0x946e (correct), seq 0,
105 | ack 1127217464, win 0, length 0
106 |
107 | 15:27:19.192319 IP (tos 0x0, ttl 64, id 57861, offset 0, flags [DF],
108 | proto TCP (6), length 60) 127.0.0.1.50720 > 127.0.0.1.2001: Flags [S], cksum
109 | 0xfe30 (incorrect -> 0xb3db), seq 1553087697, win 65495, options [mss
110 | 65495,sackOK,TS val 1342235856 ecr 0,nop,wscale 7], length 0 15:27:19.192345
111 | IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP (6), length 60)
112 | 127.0.0.1.2000 > 127.0.0.1.50720: Flags [S.], cksum 0xfe30 (incorrect ->
113 | 0x7bf5), seq 2242477415, ack 1553087698, win 65483, options [mss
114 | 65495,sackOK,TS val 1342235856 ecr 1342235856,nop,wscale 7], length 0
115 | 15:27:19.192359 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto TCP
116 | (6), length 40) 127.0.0.1.50720 > 127.0.0.1.2001: Flags [R], cksum 0x4a89
117 | (incorrect -> 0x4a88), seq 1553087698, win 0, length 0
118 | */
119 | return TC_ACT_OK;
120 | }
121 | return TC_ACT_OK;
122 | }
123 | // eBPF hooks - This is where the magic happens!
124 | SEC("tc_in")
125 | int tc_ingress(struct __sk_buff *skb) { return redirect_tcp(skb, true); }
126 |
127 | SEC("tc_egress")
128 | int tc_egress_(struct __sk_buff *skb) { return redirect_tcp(skb, false); }
129 |
--------------------------------------------------------------------------------
/eBPF/redirect/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/thebsdbox/emperium/eBPF/redirect
2 |
3 | go 1.21.3
4 |
5 | require (
6 | github.com/cilium/ebpf v0.16.0
7 | github.com/sirupsen/logrus v1.9.3
8 | github.com/vishvananda/netlink v1.3.0
9 | golang.org/x/sys v0.24.0
10 | )
11 |
12 | require (
13 | github.com/vishvananda/netns v0.0.4 // indirect
14 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 // indirect
15 | )
16 |
--------------------------------------------------------------------------------
/eBPF/redirect/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cilium/ebpf v0.16.0 h1:+BiEnHL6Z7lXnlGUsXQPPAE7+kenAd4ES8MQ5min0Ok=
2 | github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEngfwE=
3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/go-quicktest/qt v1.101.0 h1:O1K29Txy5P2OK0dGo59b7b0LR6wKfIhttaAhHUyn7eI=
7 | github.com/go-quicktest/qt v1.101.0/go.mod h1:14Bz/f7NwaXPtdYEgzsx46kqSxVwTbzVZsDC26tQJow=
8 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
9 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
10 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
11 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
12 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
13 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
14 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
15 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
16 | github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M=
17 | github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA=
18 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
19 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
20 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
21 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
22 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
23 | github.com/vishvananda/netlink v1.3.0 h1:X7l42GfcV4S6E4vHTsw48qbrV+9PVojNfIhZcwQdrZk=
24 | github.com/vishvananda/netlink v1.3.0/go.mod h1:i6NetklAujEcC6fK0JPjT8qSwWyO0HLn4UKG+hGqeJs=
25 | github.com/vishvananda/netns v0.0.4 h1:Oeaw1EM2JMxD51g9uhtC0D7erkIjgmj8+JZc26m1YX8=
26 | github.com/vishvananda/netns v0.0.4/go.mod h1:SpkAiCQRtJ6TvvxPnOSyH3BMl6unz3xZlaprSwhNNJM=
27 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 h1:Jvc7gsqn21cJHCmAWx0LiimpP18LZmUxkT5Mp7EZ1mI=
28 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
29 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
30 | golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
31 | golang.org/x/sys v0.10.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
32 | golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
33 | golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
34 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
35 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
36 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
37 |
--------------------------------------------------------------------------------
/eBPF/redirect/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "context"
6 | "errors"
7 | "flag"
8 | "fmt"
9 | "io"
10 | "net"
11 | "os"
12 | "os/signal"
13 | "syscall"
14 |
15 | log "github.com/sirupsen/logrus"
16 | "github.com/vishvananda/netlink"
17 | "golang.org/x/sys/unix"
18 |
19 | "github.com/cilium/ebpf"
20 | )
21 |
22 | //go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang -cflags "-O2 -g -Wall -Werror" redirect ./ebpf/redirect.c -- -I../../headers
23 |
24 | func main() {
25 |
26 | ifaceName := flag.String("interface", "lo", "The interface to watch network traffic on")
27 |
28 | flag.Parse()
29 |
30 | log.Info("Starting 🐝 the eBPF redirecter, on interface [%s]", *ifaceName)
31 |
32 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
33 | defer stop()
34 | // Look up the network interface by name.
35 | devID, err := net.InterfaceByName(*ifaceName)
36 | if err != nil {
37 | panic(fmt.Sprintf("lookup network iface %s: %s", *ifaceName, err))
38 | }
39 |
40 | objs := redirectObjects{}
41 |
42 | if err := loadRedirectObjects(&objs, nil); err != nil {
43 | var verr *ebpf.VerifierError
44 | if errors.As(err, &verr) {
45 | fmt.Printf("%+v\n", verr)
46 | }
47 | log.Fatalf("loading objects: %s", err)
48 | }
49 | defer objs.Close()
50 |
51 | qdisc := &netlink.GenericQdisc{
52 | QdiscAttrs: netlink.QdiscAttrs{
53 | LinkIndex: devID.Index,
54 | Handle: netlink.MakeHandle(0xffff, 0),
55 | Parent: netlink.HANDLE_INGRESS,
56 | },
57 | QdiscType: "clsact",
58 | }
59 |
60 | err = netlink.QdiscReplace(qdisc)
61 | if err != nil {
62 | log.Fatalf("could not get replace qdisc: %v", err)
63 | }
64 | log.Info("Loaded TC QDisc")
65 |
66 | filterIngress := &netlink.BpfFilter{
67 | FilterAttrs: netlink.FilterAttrs{
68 | LinkIndex: devID.Index,
69 | Parent: netlink.HANDLE_MIN_INGRESS,
70 | Handle: 1,
71 | Protocol: unix.ETH_P_ALL,
72 | },
73 | Fd: objs.TcIngress.FD(),
74 | Name: objs.TcIngress.String(),
75 | DirectAction: true,
76 | }
77 |
78 | if err := netlink.FilterReplace(filterIngress); err != nil {
79 | log.Fatalf("failed to replace tc filter: %v", err)
80 | }
81 |
82 | filterEgress := &netlink.BpfFilter{
83 | FilterAttrs: netlink.FilterAttrs{
84 | LinkIndex: devID.Index,
85 | Parent: netlink.HANDLE_MIN_EGRESS,
86 | Handle: 1,
87 | Protocol: unix.ETH_P_ALL,
88 | },
89 | Fd: objs.TcEgress.FD(),
90 | Name: objs.TcEgress.String(),
91 | DirectAction: true,
92 | }
93 |
94 | if err := netlink.FilterReplace(filterEgress); err != nil {
95 | log.Fatalf("failed to replace tc filter: %v", err)
96 | }
97 |
98 | log.Printf("Press Ctrl-C to exit and remove the program")
99 |
100 | // Drop the logs
101 | go cat()
102 | <-ctx.Done() // We wait here
103 |
104 | log.Info("Removing eBPF programs")
105 |
106 | link, err := netlink.LinkByName(*ifaceName)
107 | if err != nil {
108 | log.Fatalf("could not find iface: %v", err)
109 | }
110 |
111 | f, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS)
112 | if err != nil {
113 | log.Fatalf("could not list filters: %v", err)
114 | }
115 |
116 | if len(f) == 0 {
117 | log.Error("Unable to clean any filters")
118 | }
119 | for x := range f {
120 | err = netlink.FilterDel(f[x])
121 | if err != nil {
122 | log.Fatalf("could not get remove filter: %v", err)
123 | }
124 | }
125 |
126 | f, err = netlink.FilterList(link, netlink.HANDLE_MIN_EGRESS)
127 | if err != nil {
128 | log.Fatalf("could not list filters: %v", err)
129 | }
130 |
131 | if len(f) == 0 {
132 | log.Error("Unable to clean any filters")
133 | }
134 | for x := range f {
135 | err = netlink.FilterDel(f[x])
136 | if err != nil {
137 | log.Fatalf("could not get remove filter: %v", err)
138 | }
139 | }
140 | }
141 | func readLines(r io.Reader) {
142 | rd := bufio.NewReader(r)
143 | for {
144 | line, err := rd.ReadString('\n')
145 | if err == io.EOF {
146 | break
147 | }
148 | if err != nil {
149 | log.Fatal(err)
150 | }
151 |
152 | fmt.Printf("%s", line)
153 |
154 | }
155 | }
156 |
157 | func cat() {
158 | file, err := os.Open("/sys/kernel/tracing/trace_pipe")
159 | if err != nil {
160 | log.Fatal(err)
161 | }
162 | defer file.Close()
163 | readLines(file)
164 | }
165 |
--------------------------------------------------------------------------------
/eBPF/response/ebpf/response.c:
--------------------------------------------------------------------------------
1 | // +build ignore
2 |
3 | #include "../../header/vmlinux.h"
4 | #include
5 | #include
6 | #include
7 |
8 | #pragma pack(1)
9 |
10 | char __license[] SEC("license") = "GPL";
11 |
12 | // TC Return codes
13 | #define TC_ACT_OK 0
14 | #define TC_ACT_SHOT 2
15 |
16 | #define ETH_P_IP 0x0800 /* Internet Protocol packet */
17 | #define ETH_HLEN 14 /*Ethernet Header Length */
18 | #define ETH_ALEN 6
19 |
20 | #define IP_SRC_OFF (ETH_HLEN + offsetof(struct iphdr, saddr))
21 | #define IP_DST_OFF (ETH_HLEN + offsetof(struct iphdr, daddr))
22 |
23 | static inline int swap_udp(struct __sk_buff *skb) {
24 | // Get pointers to the beginning and end
25 | void *data_end = (void *)(long)skb->data_end;
26 | void *data = (void *)(long)skb->data;
27 |
28 | // Point to ethernet header
29 | struct ethhdr *eth = data;
30 | __u16 h_proto;
31 | __u64 nh_off = 0;
32 | nh_off = sizeof(*eth);
33 |
34 | if (data + nh_off > data_end) {
35 | return TC_ACT_OK;
36 | }
37 |
38 | // Get protocol
39 | h_proto = eth->h_proto;
40 |
41 | // if it is IP continue
42 | if (h_proto == bpf_htons(ETH_P_IP)) {
43 | struct iphdr *iph = data + nh_off;
44 |
45 | // Get pointer to IP Header
46 | if ((void *)(iph + 1) > data_end) {
47 | return TC_ACT_OK;
48 | }
49 |
50 | // Check protocol inside IP packet
51 | if (iph->protocol != IPPROTO_UDP) {
52 | return TC_ACT_OK;
53 | }
54 | __u32 ip_hlen = 0;
55 | //__u32 poffset = 0;
56 | //__u32 plength = 0;
57 | // __u32 ip_total_length = bpf_ntohs(iph->tot_len);
58 |
59 | ip_hlen = iph->ihl << 2;
60 |
61 | if (ip_hlen < sizeof(*iph)) {
62 | return TC_ACT_OK;
63 | }
64 | struct udphdr *udph = data + nh_off + sizeof(*iph);
65 |
66 | if ((void *)(udph + 1) > data_end) {
67 | return TC_ACT_OK;
68 | }
69 | __u16 src_port = bpf_ntohs(udph->source);
70 | __u16 dst_port = bpf_ntohs(udph->dest);
71 |
72 | // Is the destination port the correct one?
73 | if (dst_port == 9000) {
74 | bpf_printk("UDP %d %d", src_port, dst_port);
75 |
76 | u32 payload_offset = sizeof(*eth) + sizeof(*iph) + sizeof(*udph);
77 | u32 payload_length = iph->tot_len - (sizeof(*iph) + sizeof(*udph));
78 |
79 | if (payload_length < 3) {
80 | return TC_ACT_OK;
81 | }
82 |
83 | uint8_t data[4];
84 | u32 ret = bpf_skb_load_bytes(skb, payload_offset, data, sizeof(data) - 1);
85 | if (ret) {
86 | bpf_printk("error");
87 | return TC_ACT_OK;
88 | }
89 | data[3] = '\0'; // null terminate the string
90 | bpf_printk("data: %s", data);
91 |
92 | u32 data_offset = sizeof(*eth) + sizeof(*iph) + sizeof(*udph);
93 |
94 | data[0] = '?';
95 |
96 | ret = bpf_skb_store_bytes(skb, data_offset, &data, sizeof(data),
97 | BPF_F_RECOMPUTE_CSUM);
98 |
99 | // Something doesn't seem right
100 |
101 | /* We'll store the mac addresses (L2) */
102 | __u8 src_mac[ETH_ALEN];
103 | __u8 dst_mac[ETH_ALEN];
104 | __builtin_memcpy(src_mac, eth->h_source, ETH_ALEN);
105 | __builtin_memcpy(dst_mac, eth->h_dest, ETH_ALEN);
106 |
107 | /* ip addresses (L3) */
108 | __be32 src_ip = iph->saddr;
109 | __be32 dst_ip = iph->daddr;
110 |
111 | /* and source/destination ports (L4) */
112 | __be16 dest_port = udph->dest;
113 | __be16 src_port = udph->source;
114 |
115 | /* and then swap them all */
116 |
117 | /* Swap the mac addresses */
118 | bpf_skb_store_bytes(skb, offsetof(struct ethhdr, h_source), dst_mac,
119 | ETH_ALEN, 0);
120 | bpf_skb_store_bytes(skb, offsetof(struct ethhdr, h_dest), src_mac,
121 | ETH_ALEN, 0);
122 |
123 | /* Swap the ip addresses
124 | * swapping the ips does not require checksum recalculation,
125 | * but we might want to reduce the TTL to prevent packets infinitely
126 | * looping between us and another device that does not reduce the TTL */
127 | bpf_skb_store_bytes(skb,
128 | sizeof(struct ethhdr) + offsetof(struct iphdr, saddr),
129 | &dst_ip, sizeof(dst_ip), 0);
130 | bpf_skb_store_bytes(skb,
131 | sizeof(struct ethhdr) + offsetof(struct iphdr, daddr),
132 | &src_ip, sizeof(src_ip), 0);
133 |
134 | /* Swap the source and destination ports in the udp packet */
135 | bpf_skb_store_bytes(skb,
136 | sizeof(struct ethhdr) + sizeof(struct iphdr) +
137 | offsetof(struct udphdr, source),
138 | &dest_port, sizeof(dest_port), 0);
139 | bpf_skb_store_bytes(skb,
140 | sizeof(struct ethhdr) + sizeof(struct iphdr) +
141 | offsetof(struct udphdr, dest),
142 | &src_port, sizeof(src_port), 0);
143 |
144 | /* And then send it back from wherever it's come from */
145 | ret = bpf_clone_redirect(skb, skb->ifindex, 0);
146 | if (ret) {
147 | bpf_printk("bpf_clone_redirect error: %d", ret);
148 | }
149 | /* Since we've handled the packet, drop it */
150 | return TC_ACT_SHOT;
151 | }
152 |
153 | return TC_ACT_OK;
154 | }
155 | return TC_ACT_OK;
156 | }
157 |
158 | // eBPF hooks - This is where the magic happens!
159 | SEC("tc_in")
160 | int tc_ingress(struct __sk_buff *skb) { return swap_udp(skb); }
161 |
162 | SEC("tc_egress")
163 | int tc_egress_(struct __sk_buff *skb) { return swap_udp(skb); }
164 |
--------------------------------------------------------------------------------
/eBPF/response/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/thebsdbox/eBPF-Summit-2024-CTF/eBPF/response
2 |
3 | go 1.21.3
4 |
5 | require (
6 | github.com/praserx/ipconv v1.2.2
7 | github.com/sirupsen/logrus v1.9.3
8 | github.com/vishvananda/netlink v1.1.0
9 | golang.org/x/sys v0.24.0
10 | )
11 |
12 | require (
13 | github.com/cilium/ebpf v0.16.0 // indirect
14 | github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df // indirect
15 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 // indirect
16 | )
17 |
--------------------------------------------------------------------------------
/eBPF/response/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cilium/ebpf v0.16.0 h1:+BiEnHL6Z7lXnlGUsXQPPAE7+kenAd4ES8MQ5min0Ok=
2 | github.com/cilium/ebpf v0.16.0/go.mod h1:L7u2Blt2jMM/vLAVgjxluxtBKlz3/GWjB0dMOEngfwE=
3 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
4 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
5 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
7 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
8 | github.com/praserx/ipconv v1.2.2 h1:oz4XXNjywgoJRAnSymUET03OwSLL7JDVjQQEtl08XV8=
9 | github.com/praserx/ipconv v1.2.2/go.mod h1:DSy+AKre/e3w/npsmUDMio+OR/a2rvmMdI7rerOIgqI=
10 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
11 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
12 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
13 | github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=
14 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
15 | github.com/vishvananda/netlink v1.1.0 h1:1iyaYNBLmP6L0220aDnYQpo1QEV4t4hJ+xEEhhJH8j0=
16 | github.com/vishvananda/netlink v1.1.0/go.mod h1:cTgwzPIzzgDAYoQrMm0EdrjRUBkTqKYppBueQtXaqoE=
17 | github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df h1:OviZH7qLw/7ZovXvuNyL3XQl8UFofeikI1NW1Gypu7k=
18 | github.com/vishvananda/netns v0.0.0-20191106174202-0a2b9b5464df/go.mod h1:JP3t17pCcGlemwknint6hfoeCVQrEMVwxRLRjXpq+BU=
19 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2 h1:Jvc7gsqn21cJHCmAWx0LiimpP18LZmUxkT5Mp7EZ1mI=
20 | golang.org/x/exp v0.0.0-20230224173230-c95f2b4c22f2/go.mod h1:CxIveKay+FTh1D0yPZemJVgC/95VzuuOLq5Qi4xnoYc=
21 | golang.org/x/sys v0.0.0-20190606203320-7fc4e5ec1444/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
22 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
23 | golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
24 | golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
25 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
26 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
27 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
28 |
--------------------------------------------------------------------------------
/eBPF/response/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "context"
6 | "errors"
7 | "flag"
8 | "fmt"
9 | "io"
10 | "net"
11 | "os"
12 | "os/signal"
13 | "syscall"
14 |
15 | "github.com/cilium/ebpf"
16 | log "github.com/sirupsen/logrus"
17 | "github.com/vishvananda/netlink"
18 | "golang.org/x/sys/unix"
19 | )
20 |
21 | //go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc clang -cflags "-O2 -g -Wall -Werror" udp ./ebpf/response.c -- -I../../headers
22 |
23 | func main() {
24 |
25 | ifaceName := flag.String("interface", "lo", "The interface to watch network traffic on")
26 | flag.Parse()
27 |
28 | log.Infof("Starting 🐝 the eBPF UDP watcher, on interface [%s]", *ifaceName)
29 |
30 | ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
31 | defer stop()
32 | // Look up the network interface by name.
33 | devID, err := net.InterfaceByName(*ifaceName)
34 | if err != nil {
35 | log.Fatalf("lookup network iface %s: %s", *ifaceName, err)
36 | }
37 |
38 | // Load pre-compiled programs into the kernel.
39 | objs := udpObjects{}
40 | if err := loadUdpObjects(&objs, nil); err != nil {
41 | var verr *ebpf.VerifierError
42 | if errors.As(err, &verr) {
43 | fmt.Printf("%+v\n", verr)
44 | }
45 | log.Fatalf("loading objects: %s", err)
46 | }
47 |
48 | defer objs.Close()
49 | qdisc := &netlink.GenericQdisc{
50 | QdiscAttrs: netlink.QdiscAttrs{
51 | LinkIndex: devID.Index,
52 | Handle: netlink.MakeHandle(0xffff, 0),
53 | Parent: netlink.HANDLE_INGRESS,
54 | },
55 | QdiscType: "clsact",
56 | }
57 |
58 | err = netlink.QdiscReplace(qdisc)
59 | if err != nil {
60 | log.Fatalf("could not get replace qdisc: %v", err)
61 | }
62 | log.Info("Loaded TC QDisc")
63 |
64 | filterIngress := &netlink.BpfFilter{
65 | FilterAttrs: netlink.FilterAttrs{
66 | LinkIndex: devID.Index,
67 | Parent: netlink.HANDLE_MIN_INGRESS,
68 | Handle: 1,
69 | Protocol: unix.ETH_P_ALL,
70 | },
71 | Fd: objs.TcIngress.FD(),
72 | Name: objs.TcIngress.String(),
73 | DirectAction: true,
74 | }
75 |
76 | if err := netlink.FilterReplace(filterIngress); err != nil {
77 | log.Fatalf("failed to replace tc filter: %v", err)
78 | }
79 |
80 | filterEgress := &netlink.BpfFilter{
81 | FilterAttrs: netlink.FilterAttrs{
82 | LinkIndex: devID.Index,
83 | Parent: netlink.HANDLE_MIN_EGRESS,
84 | Handle: 1,
85 | Protocol: unix.ETH_P_ALL,
86 | },
87 | Fd: objs.TcEgress.FD(),
88 | Name: objs.TcEgress.String(),
89 | DirectAction: true,
90 | }
91 |
92 | if err := netlink.FilterReplace(filterEgress); err != nil {
93 | log.Fatalf("failed to replace tc filter: %v", err)
94 | }
95 |
96 | log.Printf("Press Ctrl-C to exit and remove the program")
97 |
98 | // Drop the logs
99 | go cat()
100 | <-ctx.Done() // We wait here
101 | log.Info("Removing eBPF programs")
102 |
103 | link, err := netlink.LinkByName(*ifaceName)
104 | if err != nil {
105 | log.Fatalf("could not find iface: %v", err)
106 | }
107 |
108 | f, err := netlink.FilterList(link, netlink.HANDLE_MIN_INGRESS)
109 | if err != nil {
110 | log.Fatalf("could not list filters: %v", err)
111 | }
112 |
113 | if len(f) == 0 {
114 | log.Error("Unable to clean any filters")
115 | }
116 | for x := range f {
117 | err = netlink.FilterDel(f[x])
118 | if err != nil {
119 | log.Fatalf("could not get remove filter: %v", err)
120 | }
121 | }
122 |
123 | f, err = netlink.FilterList(link, netlink.HANDLE_MIN_EGRESS)
124 | if err != nil {
125 | log.Fatalf("could not list filters: %v", err)
126 | }
127 |
128 | if len(f) == 0 {
129 | log.Error("Unable to clean any filters")
130 | }
131 | for x := range f {
132 | err = netlink.FilterDel(f[x])
133 | if err != nil {
134 | log.Fatalf("could not get remove filter: %v", err)
135 | }
136 | }
137 | }
138 |
139 | func readLines(r io.Reader) {
140 | rd := bufio.NewReader(r)
141 | for {
142 | line, err := rd.ReadString('\n')
143 | if err == io.EOF {
144 | break
145 | }
146 | if err != nil {
147 | log.Fatal(err)
148 | }
149 |
150 | fmt.Printf("%s", line)
151 |
152 | }
153 | }
154 |
155 | func cat() {
156 | file, err := os.Open("/sys/kernel/tracing/trace_pipe")
157 | if err != nil {
158 | log.Fatal(err)
159 | }
160 | defer file.Close()
161 | readLines(file)
162 | }
163 |
--------------------------------------------------------------------------------