├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── cmd
├── root.go
└── start.go
├── demo
├── LibreCon2022-eBFP.mp4
└── demo.md
├── go.mod
├── go.sum
├── main.go
├── pkg
└── ebpf
│ ├── bpf_bpfeb.go
│ ├── bpf_bpfeb.o
│ ├── bpf_bpfel.go
│ ├── bpf_bpfel.o
│ ├── ebpf.go
│ └── src
│ ├── ebpf
│ └── sk_dispatch.c
│ └── headers
│ ├── LICENSE.BSD-2-Clause
│ ├── bpf_endian.h
│ ├── bpf_helper_defs.h
│ ├── bpf_helpers.h
│ ├── bpf_tracing.h
│ ├── common.h
│ └── update.sh
└── test
├── e2e.bats
├── e2e.post
└── e2e.pre
/.gitignore:
--------------------------------------------------------------------------------
1 | bin/
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type 'show c' for details.
659 |
660 | The hypothetical commands 'show w' and 'show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | .PHONY: generate build-cli build-test run test stop bpftool clean clean-ebpf clean-linux
2 | .DEFAULT_TARGET = run
3 |
4 | # main
5 | BIN_DIR=bin
6 | BIN_NAME=sk
7 | PID=$(pidof bin/sk_dispatch)
8 |
9 | # export compiler and flags
10 | CLANG := clang
11 | CFLAGS := -g -O2 -Wall -Wextra $(CFLAGS)
12 | generate: export BPF_CLANG := $(CLANG)
13 | generate: export BPF_CFLAGS := $(CFLAGS)
14 | generate:
15 | cd pkg/ebpf && go generate -v ./...
16 |
17 | build: generate
18 | @echo -e "# bin/sk build started"
19 | mkdir -p bin
20 | go build -o ${BIN_DIR}/${BIN_NAME} .
21 |
22 | test-e2e: build
23 | @echo -e "\n# running e2e test"
24 | @./test/e2e.pre
25 | @./test/e2e.bats
26 | @./test/e2e.post
27 |
28 | e2e: test-e2e clean
29 |
30 | stop:
31 | @echo -e "\n# kill sk"
32 | @pkill ${BIN_NAME}
33 |
34 | clean: stop
35 | @echo -e "# clean binaries"
36 | @rm ${BIN_DIR}/${BIN_NAME}
37 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # sklookup-go
2 |
3 | - [sklookup-go](#sklookup-go)
4 | - [What is sk_lookup](#what-is-sk_lookup-wip-section)
5 | - [Use cases](#use-cases-wip-section)
6 | - [Requirements](#requirements)
7 | - [Usage](#usage)
8 | - [As golang package](#as-golang-package)
9 | - [As cli](#as-cli)
10 | - [Tested OS, kernels and libbpf](#tested-os-kernels-and-libbpf)
11 | - [Ubuntu 22.04.1 LTS - Jammy](#ubuntu-22041-lts---jammy)
12 | - [Fedora release 36 (Thirty Six)](#fedora-release-36-thirty-six)
13 | - [To Do](#to-do)
14 | - [Demonstration](#demonstration)
15 |
16 | ## What is sk_lookup
17 |
18 | Fast introduction to technologies used:
19 |
20 | - eBPF
21 | - BTF
22 | - bpf2go
23 | - sk_lookup
24 |
25 | ## Use cases
26 |
27 | - Attaching ports to an already running service
28 | - Serving applications from multiple ports while binding only to one
29 | - Ideal solution for proxies
30 | - Rule of cool: why not use eBPF when it's just simply so cool?
31 |
32 | ## Requirements
33 |
34 | - golang 1.18
35 | - libbpf
36 | - libbpf-dev
37 |
38 | ## Usage
39 |
40 | ### As golang package
41 |
42 | - Additional ports can be attached to a specific pid, when the caller and target processes are not the same.
43 |
44 | ```go
45 | import "github.com/fbac/sklookup-go/pkg/ebpf"
46 |
47 | func main() {
48 | name := "AppName"
49 | pid := 165929
50 | ports := []uint16{222, 2222, 1111, 7878}
51 | loglevel := "debug"
52 |
53 | ebpf.NewExternalDispatcher(name, pid, ports, loglevel).InitializeDispatcher()
54 | }
55 | ```
56 |
57 | - Or by attaching a file descriptor, when the caller and target processes are the same.
58 |
59 | ```go
60 | import "github.com/fbac/sklookup-go/pkg/ebpf"
61 |
62 | func main() {
63 | // Resolve and listen to and create a listener into some address
64 | addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("%v", ":443"))
65 | if err != nil {
66 | log.Fatalln(err)
67 | }
68 |
69 | listener, err := net.ListenTCP("tcp", addr)
70 | if err != nil {
71 | log.Fatalln(err)
72 | }
73 | defer listener.Close()
74 |
75 | // Get listener's file descriptor by retrieving it as a file
76 | f, _ := listener.File()
77 | defer f.Close()
78 |
79 | name := "AppName"
80 | fd := f.Fd() // Pass the fd into eBPF dispatcher
81 | ports := []uint16{1025, 1026, 1027, 1028}
82 | loglevel := "debug"
83 |
84 | ebpf.NewInternalDispatcher(name, fd, ports, loglevel).InitializeDispatcher()
85 | }
86 | ```
87 |
88 | ### As cli
89 |
90 | - Build
91 |
92 | ```bash
93 | make build-cli
94 | ```
95 |
96 | - Usage options
97 | - Note that `sk` must be run as root, since it requires loading eBPF programs and maps into kernel memory. Otherwise your system should allow unprivileged eBPF code, and that's not secure and not a scope of this project.
98 |
99 | ```bash
100 | $ sudo bin/sk start -h
101 |
102 | Start targets a PID, and steer all the connections from the provided additional ports to the socket where it's listening
103 |
104 | Usage:
105 | sk start [flags]
106 |
107 | Flags:
108 | -h, --help help for start
109 | -l, --loglevel string Log-level to run the app. Available: info, debug, panic. (default "info")
110 | -n, --name string Descriptive name for the application (default "sk_lookup")
111 | --pid int Target process PID (default -1)
112 | -p, --ports uints Additional ports (default [])
113 | -t, --toggle Help message for toggle
114 | ```
115 |
116 | ### Tested OS, kernels and libbpf
117 |
118 | The proxy has been tested in the following OS, with the respective kernel and bpf tools versions.
119 |
120 | Also, it's **required** to run it as **root** user.
121 |
122 | The system must be able to run BPF programs.
123 |
124 | #### Ubuntu 22.04.1 LTS - Jammy
125 |
126 | - Kernel `5.15.0-47-generic`
127 |
128 | - golang 1.18
129 |
130 | - BPF packages:
131 |
132 | ```bash
133 | binutils-bpf/jammy 2.38-2ubuntu1+3 amd64
134 | bpftrace/jammy 0.14.0-1 amd64
135 | libbpf-dev/jammy 1:0.5.0-1 amd64
136 | libbpf0/jammy,now 1:0.5.0-1 amd64 [installed,automatic]
137 | ```
138 |
139 | #### Fedora release 36 (Thirty Six)
140 |
141 | - Kernel `5.18.17-200.fc36.x86_64`
142 | - golang 1.18
143 | - BPF packages:
144 |
145 | ```bash
146 | libbpf-0.7.0-3.fc36.x86_64
147 | libbpf-devel-0.7.0-3.fc36.x86_64
148 | bpftrace-0.14.1-1.fc36.x86_64
149 | bpftool-5.19.4-200.fc36.x86_64
150 | ```
151 |
152 | ## To Do
153 |
154 | - Use os.Env and/or viper to supply parameters
155 | - Finish README.md
156 |
157 | ## Demonstration
158 |
159 | Let's add additional ports to an old good sshd server
160 |
161 | Said sshd server is running inside a virtual machine.
162 |
163 | - Scanning open ports
164 |
165 | ```bash
166 | # nmap -sT -p 1-10000 192.168.122.172
167 |
168 | Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-19 16:21 CEST
169 | Nmap scan report for 192.168.122.172
170 | Host is up (0.00020s latency).
171 | Not shown: 9999 closed tcp ports (conn-refused)
172 | PORT STATE SERVICE
173 | 22/tcp open ssh
174 | MAC Address: 52:54:00:74:4B:83 (QEMU virtual NIC)
175 |
176 | Nmap done: 1 IP address (1 host up) scanned in 0.66 seconds
177 | ```
178 |
179 | - Build `sk` and copy into the vm
180 |
181 | ```bash
182 | $ make build-cli
183 |
184 | # sklook build started
185 | mkdir -p bin
186 | go build -o bin/sk .
187 |
188 | $ scp bin/sk root@192.168.122.172:/tmp
189 | sk 100% 5709KB 17.6MB/s 00:00
190 | ```
191 |
192 | - Login into the vm and get sshd PID
193 |
194 | ```bash
195 | $ pidof sshd
196 | 627
197 | ```
198 |
199 | - Run `sk` against the target PID and with as many as additional ports as needed. (max ports 1024)
200 |
201 | ```bash
202 | root@vm:~# /tmp/sk start --pid 627 --ports 2,22,222,1111,1010,9999 --name sshd-vm --loglevel debug &
203 | [1] 2109
204 |
205 | root@vm:~# {"level":"info","time":"2022-09-19T14:27:40Z","message":"eBPF dispatcher with name sshd-vm initializing"}
206 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"Prog SkLookup(sk_dispatch)#6 is pinned: true"}
207 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"Map SockMap(target_socket)#5 is pinned: true"}
208 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"Map Hash(add_ports)#4 is pinned: true"}
209 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"listener FD: 7"}
210 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 2"}
211 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 22"}
212 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 222"}
213 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 1111"}
214 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 1010"}
215 | {"level":"debug","time":"2022-09-19T14:27:40Z","message":"adding port: 9999"}
216 | {"level":"info","time":"2022-09-19T14:27:40Z","message":"eBPF dispatcher sshd-vm initialized. Dispatching traffic from ports [2 22 222 1111 1010 9999] to original pid 627"}
217 | ```
218 |
219 | - From your host, scan again the vm open ports
220 |
221 | ```bash
222 | [root@hyperion ~]# nmap -sT -p 1-10000 192.168.122.172
223 | Starting Nmap 7.92 ( https://nmap.org ) at 2022-09-19 16:29 CEST
224 | Nmap scan report for 192.168.122.172
225 | Host is up (0.00019s latency).
226 | Not shown: 9994 closed tcp ports (conn-refused)
227 | PORT STATE SERVICE
228 | 2/tcp open compressnet
229 | 22/tcp open ssh
230 | 222/tcp open rsh-spx
231 | 1010/tcp open surf
232 | 1111/tcp open lmsocialserver
233 | 9999/tcp open abyss
234 | MAC Address: 52:54:00:74:4B:83 (QEMU virtual NIC)
235 |
236 | Nmap done: 1 IP address (1 host up) scanned in 0.49 seconds
237 | ```
238 |
239 | - Try to connect to any of them
240 |
241 | ```bash
242 | [root@localhost ~]# ssh root@192.168.122.172 -p 9999
243 |
244 | The authenticity of host '[192.168.122.172]:9999 ([192.168.122.172]:9999)' can't be established.
245 | ED25519 key fingerprint is SHA256:MsHOzsCjHKvahbf45QnFgxpEaIF7mdhCWGiKOs8vPns.
246 | This key is not known by any other names
247 | Are you sure you want to continue connecting (yes/no/[fingerprint])?
248 | ```
249 |
250 | - In the vm, the pinned eBPF program and maps are pinned in a bpf filesystem
251 |
252 | ```bash
253 | root@proxy-last:~# ls -l //sys/fs/bpf/
254 | total 0
255 | -rw------- 1 root root 0 Sep 19 14:27 dispatch_link-sshd-vm
256 | -rw------- 1 root root 0 Sep 19 14:27 dispatch_prog-sshd-vm
257 | -rw------- 1 root root 0 Sep 19 14:27 port-sshd-vm
258 | -rw------- 1 root root 0 Sep 19 14:27 sock-sshd-vm
259 | ```
260 |
261 | - Also, the eBPF program and maps can be debugged as usual using `bpftool`
262 |
263 | ```bash
264 | [root@localhost ~]# bpftool prog show pinned /sys/fs/bpf/dispatch_prog-sshd-vm
265 |
266 | 201: sk_lookup name sk_dispatch tag da043673afd29081 gpl
267 | loaded_at 2022-09-19T16:34:02+0200 uid 0
268 | xlated 272B jited 156B memlock 4096B map_ids 270,271
269 | btf_id 380
270 | pids sk(423122)
271 | ```
272 |
273 | - Check pinned maps by id (or by path)
274 |
275 | ```bash
276 | [root@localhost ~]# bpftool map show id 271
277 |
278 | 271: sockmap name target_socket flags 0x0
279 | key 4B value 8B max_entries 1 memlock 4096B
280 | pids sk(423122)
281 | ```
282 |
283 | - Check map contents
284 |
285 | ```bash
286 | [root@hyperion ~]# bpftool map dump pinned /sys/fs/bpf/sock-sshd-vm
287 | key: 00 00 00 00 value: 04 20 00 00 00 00 00 00
288 | Found 1 element
289 | ```
290 |
291 | ```bash
292 | [root@hyperion ~]# bpftool map dump pinned /sys/fs/bpf/port-sshd-vm $
293 | [{
294 | "key": 1010,
295 | "value": 0
296 | },{
297 | "key": 9999,
298 | "value": 0
299 | },{
300 | "key": 22,
301 | "value": 0
302 | },{
303 | "key": 1111,
304 | "value": 0
305 | },{
306 | "key": 222,
307 | "value": 0
308 | },{
309 | "key": 2,
310 | "value": 0
311 | }
312 | }]
313 | ```
314 |
--------------------------------------------------------------------------------
/cmd/root.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright © 2022 Francisco de Borja Aranda Castillejo me@fbac.dev
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | */
17 | package cmd
18 |
19 | import (
20 | "os"
21 |
22 | "github.com/spf13/cobra"
23 | )
24 |
25 | // rootCmd represents the base command when called without any subcommands
26 | var rootCmd = &cobra.Command{
27 | Use: "sk",
28 | Short: "Steer tcp connections using sk_lookup eBPF program",
29 | Long: `Steer tcp connections using sk_lookup eBPF program`,
30 | // Run: func(cmd *cobra.Command, args []string) { },
31 | }
32 |
33 | func Execute() {
34 | err := rootCmd.Execute()
35 | if err != nil {
36 | os.Exit(1)
37 | }
38 | }
39 |
40 | func init() {
41 | rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
42 | }
43 |
--------------------------------------------------------------------------------
/cmd/start.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright © 2022 Francisco de Borja Aranda Castillejo me@fbac.dev
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | */
17 | package cmd
18 |
19 | import (
20 | "log"
21 |
22 | "github.com/fbac/sklookup-go/pkg/ebpf"
23 | "github.com/spf13/cobra"
24 | )
25 |
26 | // startCmd represents the start command
27 | var startCmd = &cobra.Command{
28 | Use: "start",
29 | Short: "Start steering connections",
30 | Long: `Start targets a PID, and steer all the connections from the provided additional ports to the socket where it's listening`,
31 | Run: func(cmd *cobra.Command, args []string) {
32 | if isSanePid(&pid) && len(ports) > 0 {
33 | convertedPorts := isSanePorts(&ports)
34 | ebpf.NewExternalDispatcher(name, pid, convertedPorts, loglevel).InitializeDispatcher()
35 | } else {
36 | log.Printf("You must provide a sane PID and at least one additional port\n\n")
37 | cmd.Help()
38 | }
39 | },
40 | }
41 |
42 | var name string
43 | var pid int
44 | var ports []uint
45 | var loglevel string
46 |
47 | func init() {
48 | rootCmd.AddCommand(startCmd)
49 | startCmd.PersistentFlags().StringVarP(&name, "name", "n", "sk_lookup", "Descriptive name for the application")
50 | startCmd.PersistentFlags().StringVarP(&loglevel, "loglevel", "l", "info", "Log-level to run the app. Available: info, debug, panic.")
51 | startCmd.PersistentFlags().UintSliceVarP(&ports, "ports", "p", []uint{}, "Additional ports")
52 | startCmd.PersistentFlags().IntVar(&pid, "pid", -1, "Target process PID")
53 | startCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
54 | }
55 |
56 | func isSanePid(pid *int) bool {
57 | return *pid != -1
58 | }
59 |
60 | func isSanePorts(ports *[]uint) []uint16 {
61 | var ret []uint16
62 | if len(*ports) > 0 {
63 | for _, v := range *ports {
64 | ret = append(ret, uint16(v))
65 | }
66 | }
67 | return ret
68 | }
69 |
--------------------------------------------------------------------------------
/demo/LibreCon2022-eBFP.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fbac/sklookup-go/7dc555e6ffa1c8e21ae2101d431180a4fb5a820a/demo/LibreCon2022-eBFP.mp4
--------------------------------------------------------------------------------
/demo/demo.md:
--------------------------------------------------------------------------------
1 | # scan open ports
2 | nmap -sT -p 1-10000 192.168.122.202
3 |
4 | # ssh test connection
5 | ssh -p 22 ubuntu@192.168.122.202 'hostname'
6 | ssh -p 222 ubuntu@192.168.122.202 'hostname'
7 |
8 | # retrieve sshd pid, socket and file descriptor
9 | ss -tulpn4 | grep sshd
10 |
11 | # show sklookup-go usage
12 | sklookup start
13 |
14 | # run sklookup-go
15 | sklookup start -l debug -n sshd-sklookup --pid 1410 -p 222,1111,2641 &
16 |
17 | # retrieve sshd pid, socket and file descriptor
18 | ss -tulpn4 | grep sshd
19 |
20 | # scan open ports
21 | nmap -sT -p 1-10000 192.168.122.202
22 |
23 | # bpftool to check pinned program
24 | bpftool prog show pinned dispatch_prog-sshd-sklookup
25 |
26 | # bpftool to check pinned maps
27 | bpftool map show id 9
28 | bpftool map show id 10
29 |
30 |
31 | # bpftool to dump data from maps
32 | bpftool map dump pinned sock-sshd-sklookup
33 | bpftool map dump pinned port-sshd-sklookup
34 |
35 | # ssh test connection to unusual port
36 | ssh -p 2641 ubuntu@192.168.122.202 'hostname'
37 | ssh -p 2641 ubuntu@192.168.122.202
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/fbac/sklookup-go
2 |
3 | go 1.18
4 |
5 | require (
6 | github.com/cilium/ebpf v0.9.1
7 | github.com/oraoto/go-pidfd v0.1.1
8 | github.com/rs/zerolog v1.28.0
9 | github.com/spf13/cobra v1.5.0
10 | )
11 |
12 | require (
13 | github.com/inconshreveable/mousetrap v1.0.0 // indirect
14 | github.com/mattn/go-colorable v0.1.12 // indirect
15 | github.com/mattn/go-isatty v0.0.14 // indirect
16 | github.com/spf13/pflag v1.0.5 // indirect
17 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 // indirect
18 | )
19 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/cilium/ebpf v0.9.1 h1:64sn2K3UKw8NbP/blsixRpF3nXuyhz/VjRlRzvlBRu4=
2 | github.com/cilium/ebpf v0.9.1/go.mod h1:+OhNOIXx/Fnu1IE8bJz2dzOA+VSfyTfdNUVdlQnxUFY=
3 | github.com/coreos/go-systemd/v22 v22.3.3-0.20220203105225-a9a7ef127534/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
4 | github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
5 | github.com/frankban/quicktest v1.14.0 h1:+cqqvzZV87b4adx/5ayVOaYZ2CrvM4ejQvUdBzPPUss=
6 | github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
7 | github.com/google/go-cmp v0.5.6 h1:BKbKCqvP6I+rmFHt06ZmyQtvB8xAkWdhFyr0ZUNZcxQ=
8 | github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=
9 | github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
10 | github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
11 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
12 | github.com/mattn/go-colorable v0.1.12 h1:jF+Du6AlPIjs2BiUiQlKOX0rt3SujHxPnksPKZbaA40=
13 | github.com/mattn/go-colorable v0.1.12/go.mod h1:u5H1YNBxpqRaxsYJYSkiCWKzEfiAb1Gb520KVy5xxl4=
14 | github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
15 | github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
16 | github.com/oraoto/go-pidfd v0.1.1 h1:57gTETdUGYpFwRKoKph8ffgeps89DF2qlfxBFdfkHiA=
17 | github.com/oraoto/go-pidfd v0.1.1/go.mod h1:gPWelSU60MvzRX+ToMlKj9lZRkeqybg6qy8cy4+rZWE=
18 | github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
19 | github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
20 | github.com/rs/xid v1.4.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
21 | github.com/rs/zerolog v1.28.0 h1:MirSo27VyNi7RJYP3078AA1+Cyzd2GB66qy3aUHvsWY=
22 | github.com/rs/zerolog v1.28.0/go.mod h1:NILgTygv/Uej1ra5XxGf82ZFSLk58MFGAUS2o6usyD0=
23 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
24 | github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=
25 | github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=
26 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
27 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
28 | golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
29 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6 h1:foEbQz/B0Oz6YIqu/69kfXPYeFQAuuMYFkjaqXzl5Wo=
30 | golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
31 | golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4=
32 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
33 | gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
34 |
--------------------------------------------------------------------------------
/main.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright © 2022 Francisco de Borja Aranda Castillejo me@fbac.dev
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | */
17 | package main
18 |
19 | import "github.com/fbac/sklookup-go/cmd"
20 |
21 | func main() {
22 | cmd.Execute()
23 | }
24 |
--------------------------------------------------------------------------------
/pkg/ebpf/bpf_bpfeb.go:
--------------------------------------------------------------------------------
1 | // Code generated by bpf2go; DO NOT EDIT.
2 | //go:build arm64be || armbe || mips || mips64 || mips64p32 || ppc64 || s390 || s390x || sparc || sparc64
3 | // +build arm64be armbe mips mips64 mips64p32 ppc64 s390 s390x sparc sparc64
4 |
5 | package ebpf
6 |
7 | import (
8 | "bytes"
9 | _ "embed"
10 | "fmt"
11 | "io"
12 |
13 | "github.com/cilium/ebpf"
14 | )
15 |
16 | // loadBpf returns the embedded CollectionSpec for bpf.
17 | func loadBpf() (*ebpf.CollectionSpec, error) {
18 | reader := bytes.NewReader(_BpfBytes)
19 | spec, err := ebpf.LoadCollectionSpecFromReader(reader)
20 | if err != nil {
21 | return nil, fmt.Errorf("can't load bpf: %w", err)
22 | }
23 |
24 | return spec, err
25 | }
26 |
27 | // loadBpfObjects loads bpf and converts it into a struct.
28 | //
29 | // The following types are suitable as obj argument:
30 | //
31 | // *bpfObjects
32 | // *bpfPrograms
33 | // *bpfMaps
34 | //
35 | // See ebpf.CollectionSpec.LoadAndAssign documentation for details.
36 | func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
37 | spec, err := loadBpf()
38 | if err != nil {
39 | return err
40 | }
41 |
42 | return spec.LoadAndAssign(obj, opts)
43 | }
44 |
45 | // bpfSpecs contains maps and programs before they are loaded into the kernel.
46 | //
47 | // It can be passed ebpf.CollectionSpec.Assign.
48 | type bpfSpecs struct {
49 | bpfProgramSpecs
50 | bpfMapSpecs
51 | }
52 |
53 | // bpfSpecs contains programs before they are loaded into the kernel.
54 | //
55 | // It can be passed ebpf.CollectionSpec.Assign.
56 | type bpfProgramSpecs struct {
57 | SkDispatch *ebpf.ProgramSpec `ebpf:"sk_dispatch"`
58 | }
59 |
60 | // bpfMapSpecs contains maps before they are loaded into the kernel.
61 | //
62 | // It can be passed ebpf.CollectionSpec.Assign.
63 | type bpfMapSpecs struct {
64 | AddPorts *ebpf.MapSpec `ebpf:"add_ports"`
65 | TargetSocket *ebpf.MapSpec `ebpf:"target_socket"`
66 | }
67 |
68 | // bpfObjects contains all objects after they have been loaded into the kernel.
69 | //
70 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
71 | type bpfObjects struct {
72 | bpfPrograms
73 | bpfMaps
74 | }
75 |
76 | func (o *bpfObjects) Close() error {
77 | return _BpfClose(
78 | &o.bpfPrograms,
79 | &o.bpfMaps,
80 | )
81 | }
82 |
83 | // bpfMaps contains all maps after they have been loaded into the kernel.
84 | //
85 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
86 | type bpfMaps struct {
87 | AddPorts *ebpf.Map `ebpf:"add_ports"`
88 | TargetSocket *ebpf.Map `ebpf:"target_socket"`
89 | }
90 |
91 | func (m *bpfMaps) Close() error {
92 | return _BpfClose(
93 | m.AddPorts,
94 | m.TargetSocket,
95 | )
96 | }
97 |
98 | // bpfPrograms contains all programs after they have been loaded into the kernel.
99 | //
100 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
101 | type bpfPrograms struct {
102 | SkDispatch *ebpf.Program `ebpf:"sk_dispatch"`
103 | }
104 |
105 | func (p *bpfPrograms) Close() error {
106 | return _BpfClose(
107 | p.SkDispatch,
108 | )
109 | }
110 |
111 | func _BpfClose(closers ...io.Closer) error {
112 | for _, closer := range closers {
113 | if err := closer.Close(); err != nil {
114 | return err
115 | }
116 | }
117 | return nil
118 | }
119 |
120 | // Do not access this directly.
121 | //go:embed bpf_bpfeb.o
122 | var _BpfBytes []byte
123 |
--------------------------------------------------------------------------------
/pkg/ebpf/bpf_bpfeb.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fbac/sklookup-go/7dc555e6ffa1c8e21ae2101d431180a4fb5a820a/pkg/ebpf/bpf_bpfeb.o
--------------------------------------------------------------------------------
/pkg/ebpf/bpf_bpfel.go:
--------------------------------------------------------------------------------
1 | // Code generated by bpf2go; DO NOT EDIT.
2 | //go:build 386 || amd64 || amd64p32 || arm || arm64 || mips64le || mips64p32le || mipsle || ppc64le || riscv64
3 | // +build 386 amd64 amd64p32 arm arm64 mips64le mips64p32le mipsle ppc64le riscv64
4 |
5 | package ebpf
6 |
7 | import (
8 | "bytes"
9 | _ "embed"
10 | "fmt"
11 | "io"
12 |
13 | "github.com/cilium/ebpf"
14 | )
15 |
16 | // loadBpf returns the embedded CollectionSpec for bpf.
17 | func loadBpf() (*ebpf.CollectionSpec, error) {
18 | reader := bytes.NewReader(_BpfBytes)
19 | spec, err := ebpf.LoadCollectionSpecFromReader(reader)
20 | if err != nil {
21 | return nil, fmt.Errorf("can't load bpf: %w", err)
22 | }
23 |
24 | return spec, err
25 | }
26 |
27 | // loadBpfObjects loads bpf and converts it into a struct.
28 | //
29 | // The following types are suitable as obj argument:
30 | //
31 | // *bpfObjects
32 | // *bpfPrograms
33 | // *bpfMaps
34 | //
35 | // See ebpf.CollectionSpec.LoadAndAssign documentation for details.
36 | func loadBpfObjects(obj interface{}, opts *ebpf.CollectionOptions) error {
37 | spec, err := loadBpf()
38 | if err != nil {
39 | return err
40 | }
41 |
42 | return spec.LoadAndAssign(obj, opts)
43 | }
44 |
45 | // bpfSpecs contains maps and programs before they are loaded into the kernel.
46 | //
47 | // It can be passed ebpf.CollectionSpec.Assign.
48 | type bpfSpecs struct {
49 | bpfProgramSpecs
50 | bpfMapSpecs
51 | }
52 |
53 | // bpfSpecs contains programs before they are loaded into the kernel.
54 | //
55 | // It can be passed ebpf.CollectionSpec.Assign.
56 | type bpfProgramSpecs struct {
57 | SkDispatch *ebpf.ProgramSpec `ebpf:"sk_dispatch"`
58 | }
59 |
60 | // bpfMapSpecs contains maps before they are loaded into the kernel.
61 | //
62 | // It can be passed ebpf.CollectionSpec.Assign.
63 | type bpfMapSpecs struct {
64 | AddPorts *ebpf.MapSpec `ebpf:"add_ports"`
65 | TargetSocket *ebpf.MapSpec `ebpf:"target_socket"`
66 | }
67 |
68 | // bpfObjects contains all objects after they have been loaded into the kernel.
69 | //
70 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
71 | type bpfObjects struct {
72 | bpfPrograms
73 | bpfMaps
74 | }
75 |
76 | func (o *bpfObjects) Close() error {
77 | return _BpfClose(
78 | &o.bpfPrograms,
79 | &o.bpfMaps,
80 | )
81 | }
82 |
83 | // bpfMaps contains all maps after they have been loaded into the kernel.
84 | //
85 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
86 | type bpfMaps struct {
87 | AddPorts *ebpf.Map `ebpf:"add_ports"`
88 | TargetSocket *ebpf.Map `ebpf:"target_socket"`
89 | }
90 |
91 | func (m *bpfMaps) Close() error {
92 | return _BpfClose(
93 | m.AddPorts,
94 | m.TargetSocket,
95 | )
96 | }
97 |
98 | // bpfPrograms contains all programs after they have been loaded into the kernel.
99 | //
100 | // It can be passed to loadBpfObjects or ebpf.CollectionSpec.LoadAndAssign.
101 | type bpfPrograms struct {
102 | SkDispatch *ebpf.Program `ebpf:"sk_dispatch"`
103 | }
104 |
105 | func (p *bpfPrograms) Close() error {
106 | return _BpfClose(
107 | p.SkDispatch,
108 | )
109 | }
110 |
111 | func _BpfClose(closers ...io.Closer) error {
112 | for _, closer := range closers {
113 | if err := closer.Close(); err != nil {
114 | return err
115 | }
116 | }
117 | return nil
118 | }
119 |
120 | // Do not access this directly.
121 | //go:embed bpf_bpfel.o
122 | var _BpfBytes []byte
123 |
--------------------------------------------------------------------------------
/pkg/ebpf/bpf_bpfel.o:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/fbac/sklookup-go/7dc555e6ffa1c8e21ae2101d431180a4fb5a820a/pkg/ebpf/bpf_bpfel.o
--------------------------------------------------------------------------------
/pkg/ebpf/ebpf.go:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright © 2022 Francisco de Borja Aranda Castillejo me@fbac.dev
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | //go:generate go run github.com/cilium/ebpf/cmd/bpf2go -cc $BPF_CLANG -cflags $BPF_CFLAGS bpf src/ebpf/sk_dispatch.c -- -Isrc/headers
19 | package ebpf
20 |
21 | import (
22 | "C"
23 | "context"
24 | "fmt"
25 | "log"
26 | "os"
27 | "os/signal"
28 | "unsafe"
29 |
30 | "github.com/cilium/ebpf"
31 | "github.com/cilium/ebpf/link"
32 | "github.com/cilium/ebpf/rlimit"
33 | pidfd "github.com/oraoto/go-pidfd"
34 | "github.com/rs/zerolog"
35 | )
36 |
37 | const (
38 | mapKey uint32 = 0
39 | ebpfDir string = "/sys/fs/bpf/"
40 | esock string = "/sys/fs/bpf/sock"
41 | eport string = "/sys/fs/bpf/port"
42 | dispatchProg string = "/sys/fs/bpf/dispatch_prog"
43 | dispatchLink string = "/sys/fs/bpf/dispatch_link"
44 | )
45 |
46 | // EbpfDispatcher represents an instance of the eBPF sk_lookup dispatcher
47 | type ebpfDispatcher struct {
48 | Name string
49 | Log zerolog.Logger
50 | LogLevel string
51 | AdditionalPorts []uint16
52 | }
53 |
54 | type EbpfInternalDispatcher struct {
55 | ebpfDispatcher
56 | FileDescriptor uintptr
57 | }
58 |
59 | type EbpfExternalDispatcher struct {
60 | ebpfDispatcher
61 | TargetPID int
62 | }
63 |
64 | // NewExternalDispatcher returns a new instance of external eBPF dispatcher
65 | func NewExternalDispatcher(name string, pid int, ports []uint16, loglevel string) *EbpfExternalDispatcher {
66 | _, err := os.FindProcess(pid)
67 | if err != nil {
68 | panic(err)
69 | }
70 | return &EbpfExternalDispatcher{ebpfDispatcher: *newEbpfDispatcher(name, ports, loglevel), TargetPID: pid}
71 | }
72 |
73 | // NewInternalDispatcher returns a new instance of internal eBPF dispatcher
74 | func NewInternalDispatcher(name string, fd uintptr, ports []uint16, loglevel string) *EbpfInternalDispatcher {
75 | return &EbpfInternalDispatcher{ebpfDispatcher: *newEbpfDispatcher(name, ports, loglevel), FileDescriptor: fd}
76 | }
77 |
78 | func newEbpfDispatcher(name string, ports []uint16, loglevel string) *ebpfDispatcher {
79 | logger := newLogging(loglevel)
80 |
81 | if !checkValidPorts(ports) {
82 | logger.Fatal().Msgf("Ports provided not valid")
83 | }
84 | return &ebpfDispatcher{Name: name, AdditionalPorts: ports, Log: logger}
85 | }
86 |
87 | // InitializeDispatcherByPID initializes sk_lookup on a given pid
88 | func (e *EbpfExternalDispatcher) InitializeDispatcher() {
89 | ctx := newCancelableContext()
90 | e.Log.Info().Msgf("eBPF dispatcher with name %s initializing. Traffic from %v will be dispatched to PID %v", e.Name, e.AdditionalPorts, e.TargetPID)
91 |
92 | // Initialize custom vars, necessary to run more than one instance
93 | nameSockMap := fmt.Sprintf("%s-%s", esock, e.Name)
94 | namePortMap := fmt.Sprintf("%s-%s", eport, e.Name)
95 | nameDispatchProg := fmt.Sprintf("%s-%s", dispatchProg, e.Name)
96 | nameDispatchLink := fmt.Sprintf("%s-%s", dispatchLink, e.Name)
97 | if checkFileDoNotExist(nameSockMap, namePortMap, nameDispatchProg, nameDispatchLink) {
98 | e.Log.Fatal().Msgf("Check that previous eBPF files doesn't exist: %s %s %s %s", nameSockMap, namePortMap, nameDispatchProg, nameDispatchLink)
99 | }
100 |
101 | // Allow locking memory for eBPF resources
102 | if err := rlimit.RemoveMemlock(); err != nil {
103 | e.Log.Panic().Err(err).Msg("Unable to remove memlock")
104 | }
105 |
106 | // Load eBPF Program and Maps
107 | objs := bpfObjects{}
108 | if err := loadBpfObjects(&objs, nil); err != nil {
109 | log.Fatalf("loading objects: %v", err)
110 | }
111 |
112 | // Pin eBPF program and maps
113 | if err := objs.SkDispatch.Pin(nameDispatchProg); err != nil {
114 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", nameDispatchProg)
115 | }
116 | e.Log.Debug().Msgf("Prog %v is pinned: %v", objs.SkDispatch, objs.SkDispatch.IsPinned())
117 |
118 | if err := objs.TargetSocket.Pin(nameSockMap); err != nil {
119 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", nameSockMap)
120 | }
121 | e.Log.Debug().Msgf("Map %s is pinned: %v", objs.TargetSocket, objs.TargetSocket.IsPinned())
122 |
123 | if err := objs.AddPorts.Pin(namePortMap); err != nil {
124 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", namePortMap)
125 | }
126 | e.Log.Debug().Msgf("Map %s is pinned: %v", objs.AddPorts, objs.AddPorts.IsPinned())
127 |
128 | // Check if there's a need of duplicating TargetPID file descriptors
129 | var fd uintptr
130 | if e.TargetPID != os.Getpid() {
131 | fd = e.getListenerFd()
132 | } else {
133 | e.Log.Panic().Msg("Calling InitializeDispatcherByPID is not allowed where TargetPID == os.Getpid()")
134 | }
135 |
136 | // Insert fd from listener in the SockMap
137 | if err := objs.TargetSocket.Put(mapKey, unsafe.Pointer(&fd)); err != nil {
138 | e.Log.Panic().Err(err).Msgf("Unable to insert key %v into %v", fd, nameSockMap)
139 | }
140 |
141 | // Attach additional ports to the HashMap
142 | e.attachAdditionalPorts(objs.AddPorts)
143 |
144 | // Link, Pin and defer clean dispatch link
145 | lnk, err := getDispatcherLink(objs.SkDispatch)
146 | if err != nil {
147 | e.Log.Panic().Err(err).Msg("Unable to get dispatcher link")
148 | }
149 | lnk.Pin(nameDispatchLink)
150 |
151 | // Program fully initialized
152 | e.Log.Info().Msgf("eBPF dispatcher for app %s with PID %v initialized.", e.Name, e.TargetPID)
153 |
154 | // Housekeeping
155 | defer objs.Close()
156 | defer lnk.Close()
157 | defer objs.SkDispatch.Unpin()
158 | defer objs.TargetSocket.Unpin()
159 | defer objs.AddPorts.Unpin()
160 | defer lnk.Unpin()
161 |
162 | // Wait until done
163 | <-ctx.Done()
164 | }
165 |
166 | // InitializeDispatcherByFD initializes the sk_lookup on a given socket fd
167 | func (e *EbpfInternalDispatcher) InitializeDispatcher() {
168 | ctx := newCancelableContext()
169 | e.Log.Info().Msgf("eBPF dispatcher with name %s initializing. Traffic from %v will be dispatched to FD %v", e.Name, e.AdditionalPorts, e.FileDescriptor)
170 |
171 | // Initialize custom vars, necessary to run more than one instance
172 | nameSockMap := fmt.Sprintf("%s-%s", esock, e.Name)
173 | namePortMap := fmt.Sprintf("%s-%s", eport, e.Name)
174 | nameDispatchProg := fmt.Sprintf("%s-%s", dispatchProg, e.Name)
175 | nameDispatchLink := fmt.Sprintf("%s-%s", dispatchLink, e.Name)
176 | if checkFileDoNotExist(nameSockMap, namePortMap, nameDispatchProg, nameDispatchLink) {
177 | e.Log.Fatal().Msgf("Check that previous eBPF files doesn't exist: %s %s %s %s", nameSockMap, namePortMap, nameDispatchProg, nameDispatchLink)
178 | }
179 |
180 | // Allow locking memory for eBPF resources
181 | if err := rlimit.RemoveMemlock(); err != nil {
182 | e.Log.Panic().Err(err).Msg("Unable to remove memlock")
183 | }
184 |
185 | // Load eBPF Program and Maps
186 | objs := bpfObjects{}
187 | if err := loadBpfObjects(&objs, nil); err != nil {
188 | log.Fatalf("loading objects: %v", err)
189 | }
190 |
191 | // Pin eBPF program and maps
192 | if err := objs.SkDispatch.Pin(nameDispatchProg); err != nil {
193 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", nameDispatchProg)
194 | }
195 | e.Log.Debug().Msgf("Prog %v is pinned: %v", objs.SkDispatch, objs.SkDispatch.IsPinned())
196 |
197 | if err := objs.TargetSocket.Pin(nameSockMap); err != nil {
198 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", nameSockMap)
199 | }
200 | e.Log.Debug().Msgf("Map %s is pinned: %v", objs.TargetSocket, objs.TargetSocket.IsPinned())
201 |
202 | if err := objs.AddPorts.Pin(namePortMap); err != nil {
203 | e.Log.Panic().Err(err).Msgf("Unable to pin %v", namePortMap)
204 | }
205 | e.Log.Debug().Msgf("Map %s is pinned: %v", objs.AddPorts, objs.AddPorts.IsPinned())
206 |
207 | // Insert fd from listener in the SockMap
208 | if err := objs.TargetSocket.Put(mapKey, unsafe.Pointer(&e.FileDescriptor)); err != nil {
209 | e.Log.Panic().Err(err).Msgf("Unable to insert key %v into %v", e.FileDescriptor, nameSockMap)
210 | }
211 |
212 | // Attach additional ports to the HashMap
213 | e.attachAdditionalPorts(objs.AddPorts)
214 |
215 | // Link, Pin and defer clean dispatch link
216 | lnk, err := getDispatcherLink(objs.SkDispatch)
217 | if err != nil {
218 | e.Log.Panic().Err(err).Msg("Unable to get dispatcher link")
219 | }
220 | lnk.Pin(nameDispatchLink)
221 |
222 | // Program fully initialized
223 | e.Log.Info().Msgf("eBPF dispatcher for app %s with FD %v initialized.", e.Name, e.FileDescriptor)
224 |
225 | // Housekeeping
226 | defer objs.Close()
227 | defer lnk.Close()
228 | defer objs.SkDispatch.Unpin()
229 | defer objs.TargetSocket.Unpin()
230 | defer objs.AddPorts.Unpin()
231 | defer lnk.Unpin()
232 |
233 | // Wait until done
234 | <-ctx.Done()
235 | }
236 |
237 | // getListenerFd opens a file descriptor and duplicates it to be used by the eBPF program
238 | // This is an abstraction of the systemcall pidfd_getfd(pidfd_open(PID, 0), FD, 0)
239 | func (e *EbpfExternalDispatcher) getListenerFd() uintptr {
240 | // pidfd_open
241 | pidFd, err := pidfd.Open(e.TargetPID, 0)
242 | if err != nil {
243 | e.Log.Panic().Err(err).Msgf("Unable to open target pid %v", e.TargetPID)
244 | }
245 | e.Log.Trace().Msgf("getListenerFd.pidFd: %v", pidFd)
246 |
247 | // pidfd_getfd
248 | listenFd, err := pidFd.GetFd(int(pidFd), 0)
249 | if err != nil {
250 | e.Log.Panic().Err(err).Msgf("Unable to duplicate target fd %v", pidFd)
251 | }
252 | e.Log.Trace().Msgf("getListenerFd.listenFd: %v", listenFd)
253 |
254 | file := os.NewFile(uintptr(listenFd), "")
255 |
256 | return file.Fd()
257 | }
258 |
259 | // attachAdditionalPorts inserts additional ports into the ports HashMap
260 | func (e *ebpfDispatcher) attachAdditionalPorts(hashMap *ebpf.Map) {
261 | for _, v := range e.AdditionalPorts {
262 | e.Log.Debug().Msgf("adding port: %v", v)
263 | if err := hashMap.Put(v, uint8(0)); err != nil {
264 | panic(err)
265 | }
266 | }
267 | }
268 |
269 | // getDispatcherLink links the self netnamespace to the link
270 | // so the communication to the external socket can happen
271 | func getDispatcherLink(p *ebpf.Program) (*link.NetNsLink, error) {
272 | // Get self net-namespace
273 | netns, err := os.Open("/proc/self/ns/net")
274 | if err != nil {
275 | return nil, err
276 | }
277 | defer netns.Close()
278 |
279 | // Attach the network namespace to the link
280 | lnk, err := link.AttachNetNs(int(netns.Fd()), p)
281 | if err != nil {
282 | return nil, err
283 | }
284 |
285 | return lnk, nil
286 | }
287 |
288 | // checkFileDoNotExist check if provided files don't exist
289 | func checkFileDoNotExist(files ...string) bool {
290 | for _, v := range files {
291 | if _, err := os.Stat(v); err == nil {
292 | return true
293 | }
294 | }
295 | return false
296 | }
297 |
298 | func checkValidPorts(p []uint16) bool {
299 | return len(p) >= 0
300 | }
301 |
302 | // newCancelableContext returns a context that gets canceled by a SIGINT
303 | func newCancelableContext() context.Context {
304 | doneCh := make(chan os.Signal, 1)
305 | signal.Notify(doneCh, os.Interrupt)
306 |
307 | ctx := context.Background()
308 | ctx, cancel := context.WithCancel(ctx)
309 |
310 | go func() {
311 | <-doneCh
312 | cancel()
313 | }()
314 |
315 | return ctx
316 | }
317 |
318 | func newLogging(loglevel string) zerolog.Logger {
319 | logger := zerolog.New(os.Stderr).With().Timestamp().Logger()
320 | switch loglevel {
321 | case "info":
322 | zerolog.SetGlobalLevel(zerolog.InfoLevel)
323 | case "debug":
324 | zerolog.SetGlobalLevel(zerolog.DebugLevel)
325 | case "panic":
326 | zerolog.SetGlobalLevel(zerolog.PanicLevel)
327 | default:
328 | zerolog.SetGlobalLevel(zerolog.InfoLevel)
329 | }
330 | return logger
331 | }
332 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/ebpf/sk_dispatch.c:
--------------------------------------------------------------------------------
1 | /*
2 | Copyright © 2022 Francisco de Borja Aranda Castillejo me@fbac.dev
3 |
4 | This program is free software: you can redistribute it and/or modify
5 | it under the terms of the GNU General Public License as published by
6 | the Free Software Foundation, either version 3 of the License, or
7 | (at your option) any later version.
8 |
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 |
14 | You should have received a copy of the GNU General Public License
15 | along with this program. If not, see .
16 | */
17 |
18 | /*
19 | * BPF socket lookup program that dispatches connections destined to a
20 | * configured set of open ports.
21 | *
22 | * Program expects the target socket to be in the `target_socket` BPF map.
23 | * Port is considered open when an entry for that port number exists in the
24 | * `add_ports` BPF hashmap.
25 | *
26 | */
27 |
28 | #include
29 | #include
30 | #include
31 |
32 | /* Declare BPF maps */
33 |
34 | /* List of additional service ports.
35 | Key is the port number. */
36 |
37 | struct {
38 | __uint(type, BPF_MAP_TYPE_HASH);
39 | __type(key, __u16);
40 | __type(value, __u8);
41 | __uint(max_entries, 1024);
42 | } add_ports SEC(".maps");
43 |
44 | /* Target socket */
45 | struct {
46 | __uint(type, BPF_MAP_TYPE_SOCKMAP);
47 | __type(key, __u32);
48 | __type(value, __u64);
49 | __uint(max_entries, 1);
50 | } target_socket SEC(".maps");
51 |
52 | /* Dispatcher program for the echo service */
53 | SEC("sk_lookup/sk_dispatch")
54 | int sk_dispatch(struct bpf_sk_lookup *ctx)
55 | {
56 | const __u32 zero = 0;
57 | struct bpf_sock *sk;
58 | __u16 port;
59 | __u8 *open;
60 | long err;
61 |
62 | /* Is echo service enabled on packets destination port? */
63 | port = ctx->local_port;
64 | open = bpf_map_lookup_elem(&add_ports, &port);
65 | if (!open)
66 | return SK_PASS;
67 |
68 | /* Get echo server socket */
69 | sk = bpf_map_lookup_elem(&target_socket, &zero);
70 | if (!sk)
71 | return SK_DROP;
72 |
73 | /* Dispatch the packet to echo server socket */
74 | err = bpf_sk_assign(ctx, sk, 0);
75 | bpf_sk_release(sk);
76 | return err ? SK_DROP : SK_PASS;
77 | }
78 |
79 | SEC("license") const char __license[] = "Dual BSD/GPL";
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/LICENSE.BSD-2-Clause:
--------------------------------------------------------------------------------
1 | Valid-License-Identifier: BSD-2-Clause
2 | SPDX-URL: https://spdx.org/licenses/BSD-2-Clause.html
3 | Usage-Guide:
4 | To use the BSD 2-clause "Simplified" License put the following SPDX
5 | tag/value pair into a comment according to the placement guidelines in
6 | the licensing rules documentation:
7 | SPDX-License-Identifier: BSD-2-Clause
8 | License-Text:
9 |
10 | Copyright (c) . All rights reserved.
11 |
12 | Redistribution and use in source and binary forms, with or without
13 | modification, are permitted provided that the following conditions are met:
14 |
15 | 1. Redistributions of source code must retain the above copyright notice,
16 | this list of conditions and the following disclaimer.
17 |
18 | 2. Redistributions in binary form must reproduce the above copyright
19 | notice, this list of conditions and the following disclaimer in the
20 | documentation and/or other materials provided with the distribution.
21 |
22 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
23 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25 | ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
26 | LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
27 | CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
28 | SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
29 | INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
30 | CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
31 | ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
32 | POSSIBILITY OF SUCH DAMAGE.
33 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/bpf_endian.h:
--------------------------------------------------------------------------------
1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 | #ifndef __BPF_ENDIAN__
3 | #define __BPF_ENDIAN__
4 |
5 | /*
6 | * Isolate byte #n and put it into byte #m, for __u##b type.
7 | * E.g., moving byte #6 (nnnnnnnn) into byte #1 (mmmmmmmm) for __u64:
8 | * 1) xxxxxxxx nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx
9 | * 2) nnnnnnnn xxxxxxxx xxxxxxxx xxxxxxxx xxxxxxxx mmmmmmmm xxxxxxxx 00000000
10 | * 3) 00000000 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn
11 | * 4) 00000000 00000000 00000000 00000000 00000000 00000000 nnnnnnnn 00000000
12 | */
13 | #define ___bpf_mvb(x, b, n, m) ((__u##b)(x) << (b-(n+1)*8) >> (b-8) << (m*8))
14 |
15 | #define ___bpf_swab16(x) ((__u16)( \
16 | ___bpf_mvb(x, 16, 0, 1) | \
17 | ___bpf_mvb(x, 16, 1, 0)))
18 |
19 | #define ___bpf_swab32(x) ((__u32)( \
20 | ___bpf_mvb(x, 32, 0, 3) | \
21 | ___bpf_mvb(x, 32, 1, 2) | \
22 | ___bpf_mvb(x, 32, 2, 1) | \
23 | ___bpf_mvb(x, 32, 3, 0)))
24 |
25 | #define ___bpf_swab64(x) ((__u64)( \
26 | ___bpf_mvb(x, 64, 0, 7) | \
27 | ___bpf_mvb(x, 64, 1, 6) | \
28 | ___bpf_mvb(x, 64, 2, 5) | \
29 | ___bpf_mvb(x, 64, 3, 4) | \
30 | ___bpf_mvb(x, 64, 4, 3) | \
31 | ___bpf_mvb(x, 64, 5, 2) | \
32 | ___bpf_mvb(x, 64, 6, 1) | \
33 | ___bpf_mvb(x, 64, 7, 0)))
34 |
35 | /* LLVM's BPF target selects the endianness of the CPU
36 | * it compiles on, or the user specifies (bpfel/bpfeb),
37 | * respectively. The used __BYTE_ORDER__ is defined by
38 | * the compiler, we cannot rely on __BYTE_ORDER from
39 | * libc headers, since it doesn't reflect the actual
40 | * requested byte order.
41 | *
42 | * Note, LLVM's BPF target has different __builtin_bswapX()
43 | * semantics. It does map to BPF_ALU | BPF_END | BPF_TO_BE
44 | * in bpfel and bpfeb case, which means below, that we map
45 | * to cpu_to_be16(). We could use it unconditionally in BPF
46 | * case, but better not rely on it, so that this header here
47 | * can be used from application and BPF program side, which
48 | * use different targets.
49 | */
50 | #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
51 | # define __bpf_ntohs(x) __builtin_bswap16(x)
52 | # define __bpf_htons(x) __builtin_bswap16(x)
53 | # define __bpf_constant_ntohs(x) ___bpf_swab16(x)
54 | # define __bpf_constant_htons(x) ___bpf_swab16(x)
55 | # define __bpf_ntohl(x) __builtin_bswap32(x)
56 | # define __bpf_htonl(x) __builtin_bswap32(x)
57 | # define __bpf_constant_ntohl(x) ___bpf_swab32(x)
58 | # define __bpf_constant_htonl(x) ___bpf_swab32(x)
59 | # define __bpf_be64_to_cpu(x) __builtin_bswap64(x)
60 | # define __bpf_cpu_to_be64(x) __builtin_bswap64(x)
61 | # define __bpf_constant_be64_to_cpu(x) ___bpf_swab64(x)
62 | # define __bpf_constant_cpu_to_be64(x) ___bpf_swab64(x)
63 | #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__
64 | # define __bpf_ntohs(x) (x)
65 | # define __bpf_htons(x) (x)
66 | # define __bpf_constant_ntohs(x) (x)
67 | # define __bpf_constant_htons(x) (x)
68 | # define __bpf_ntohl(x) (x)
69 | # define __bpf_htonl(x) (x)
70 | # define __bpf_constant_ntohl(x) (x)
71 | # define __bpf_constant_htonl(x) (x)
72 | # define __bpf_be64_to_cpu(x) (x)
73 | # define __bpf_cpu_to_be64(x) (x)
74 | # define __bpf_constant_be64_to_cpu(x) (x)
75 | # define __bpf_constant_cpu_to_be64(x) (x)
76 | #else
77 | # error "Fix your compiler's __BYTE_ORDER__?!"
78 | #endif
79 |
80 | #define bpf_htons(x) \
81 | (__builtin_constant_p(x) ? \
82 | __bpf_constant_htons(x) : __bpf_htons(x))
83 | #define bpf_ntohs(x) \
84 | (__builtin_constant_p(x) ? \
85 | __bpf_constant_ntohs(x) : __bpf_ntohs(x))
86 | #define bpf_htonl(x) \
87 | (__builtin_constant_p(x) ? \
88 | __bpf_constant_htonl(x) : __bpf_htonl(x))
89 | #define bpf_ntohl(x) \
90 | (__builtin_constant_p(x) ? \
91 | __bpf_constant_ntohl(x) : __bpf_ntohl(x))
92 | #define bpf_cpu_to_be64(x) \
93 | (__builtin_constant_p(x) ? \
94 | __bpf_constant_cpu_to_be64(x) : __bpf_cpu_to_be64(x))
95 | #define bpf_be64_to_cpu(x) \
96 | (__builtin_constant_p(x) ? \
97 | __bpf_constant_be64_to_cpu(x) : __bpf_be64_to_cpu(x))
98 |
99 | #endif /* __BPF_ENDIAN__ */
100 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/bpf_helpers.h:
--------------------------------------------------------------------------------
1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 | #ifndef __BPF_HELPERS__
3 | #define __BPF_HELPERS__
4 |
5 | /*
6 | * Note that bpf programs need to include either
7 | * vmlinux.h (auto-generated from BTF) or linux/types.h
8 | * in advance since bpf_helper_defs.h uses such types
9 | * as __u64.
10 | */
11 | #include "bpf_helper_defs.h"
12 |
13 | #define __uint(name, val) int (*name)[val]
14 | #define __type(name, val) typeof(val) *name
15 | #define __array(name, val) typeof(val) *name[]
16 |
17 | /*
18 | * Helper macro to place programs, maps, license in
19 | * different sections in elf_bpf file. Section names
20 | * are interpreted by libbpf depending on the context (BPF programs, BPF maps,
21 | * extern variables, etc).
22 | * To allow use of SEC() with externs (e.g., for extern .maps declarations),
23 | * make sure __attribute__((unused)) doesn't trigger compilation warning.
24 | */
25 | #define SEC(name) \
26 | _Pragma("GCC diagnostic push") \
27 | _Pragma("GCC diagnostic ignored \"-Wignored-attributes\"") \
28 | __attribute__((section(name), used)) \
29 | _Pragma("GCC diagnostic pop") \
30 |
31 | /* Avoid 'linux/stddef.h' definition of '__always_inline'. */
32 | #undef __always_inline
33 | #define __always_inline inline __attribute__((always_inline))
34 |
35 | #ifndef __noinline
36 | #define __noinline __attribute__((noinline))
37 | #endif
38 | #ifndef __weak
39 | #define __weak __attribute__((weak))
40 | #endif
41 |
42 | /*
43 | * Use __hidden attribute to mark a non-static BPF subprogram effectively
44 | * static for BPF verifier's verification algorithm purposes, allowing more
45 | * extensive and permissive BPF verification process, taking into account
46 | * subprogram's caller context.
47 | */
48 | #define __hidden __attribute__((visibility("hidden")))
49 |
50 | /* When utilizing vmlinux.h with BPF CO-RE, user BPF programs can't include
51 | * any system-level headers (such as stddef.h, linux/version.h, etc), and
52 | * commonly-used macros like NULL and KERNEL_VERSION aren't available through
53 | * vmlinux.h. This just adds unnecessary hurdles and forces users to re-define
54 | * them on their own. So as a convenience, provide such definitions here.
55 | */
56 | #ifndef NULL
57 | #define NULL ((void *)0)
58 | #endif
59 |
60 | #ifndef KERNEL_VERSION
61 | #define KERNEL_VERSION(a, b, c) (((a) << 16) + ((b) << 8) + ((c) > 255 ? 255 : (c)))
62 | #endif
63 |
64 | /*
65 | * Helper macros to manipulate data structures
66 | */
67 | #ifndef offsetof
68 | #define offsetof(TYPE, MEMBER) ((unsigned long)&((TYPE *)0)->MEMBER)
69 | #endif
70 | #ifndef container_of
71 | #define container_of(ptr, type, member) \
72 | ({ \
73 | void *__mptr = (void *)(ptr); \
74 | ((type *)(__mptr - offsetof(type, member))); \
75 | })
76 | #endif
77 |
78 | /*
79 | * Helper macro to throw a compilation error if __bpf_unreachable() gets
80 | * built into the resulting code. This works given BPF back end does not
81 | * implement __builtin_trap(). This is useful to assert that certain paths
82 | * of the program code are never used and hence eliminated by the compiler.
83 | *
84 | * For example, consider a switch statement that covers known cases used by
85 | * the program. __bpf_unreachable() can then reside in the default case. If
86 | * the program gets extended such that a case is not covered in the switch
87 | * statement, then it will throw a build error due to the default case not
88 | * being compiled out.
89 | */
90 | #ifndef __bpf_unreachable
91 | # define __bpf_unreachable() __builtin_trap()
92 | #endif
93 |
94 | /*
95 | * Helper function to perform a tail call with a constant/immediate map slot.
96 | */
97 | #if __clang_major__ >= 8 && defined(__bpf__)
98 | static __always_inline void
99 | bpf_tail_call_static(void *ctx, const void *map, const __u32 slot)
100 | {
101 | if (!__builtin_constant_p(slot))
102 | __bpf_unreachable();
103 |
104 | /*
105 | * Provide a hard guarantee that LLVM won't optimize setting r2 (map
106 | * pointer) and r3 (constant map index) from _different paths_ ending
107 | * up at the _same_ call insn as otherwise we won't be able to use the
108 | * jmpq/nopl retpoline-free patching by the x86-64 JIT in the kernel
109 | * given they mismatch. See also d2e4c1e6c294 ("bpf: Constant map key
110 | * tracking for prog array pokes") for details on verifier tracking.
111 | *
112 | * Note on clobber list: we need to stay in-line with BPF calling
113 | * convention, so even if we don't end up using r0, r4, r5, we need
114 | * to mark them as clobber so that LLVM doesn't end up using them
115 | * before / after the call.
116 | */
117 | asm volatile("r1 = %[ctx]\n\t"
118 | "r2 = %[map]\n\t"
119 | "r3 = %[slot]\n\t"
120 | "call 12"
121 | :: [ctx]"r"(ctx), [map]"r"(map), [slot]"i"(slot)
122 | : "r0", "r1", "r2", "r3", "r4", "r5");
123 | }
124 | #endif
125 |
126 | /*
127 | * Helper structure used by eBPF C program
128 | * to describe BPF map attributes to libbpf loader
129 | */
130 | struct bpf_map_def {
131 | unsigned int type;
132 | unsigned int key_size;
133 | unsigned int value_size;
134 | unsigned int max_entries;
135 | unsigned int map_flags;
136 | };
137 |
138 | enum libbpf_pin_type {
139 | LIBBPF_PIN_NONE,
140 | /* PIN_BY_NAME: pin maps by name (in /sys/fs/bpf by default) */
141 | LIBBPF_PIN_BY_NAME,
142 | };
143 |
144 | enum libbpf_tristate {
145 | TRI_NO = 0,
146 | TRI_YES = 1,
147 | TRI_MODULE = 2,
148 | };
149 |
150 | #define __kconfig __attribute__((section(".kconfig")))
151 | #define __ksym __attribute__((section(".ksyms")))
152 |
153 | #ifndef ___bpf_concat
154 | #define ___bpf_concat(a, b) a ## b
155 | #endif
156 | #ifndef ___bpf_apply
157 | #define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
158 | #endif
159 | #ifndef ___bpf_nth
160 | #define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
161 | #endif
162 | #ifndef ___bpf_narg
163 | #define ___bpf_narg(...) \
164 | ___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
165 | #endif
166 |
167 | #define ___bpf_fill0(arr, p, x) do {} while (0)
168 | #define ___bpf_fill1(arr, p, x) arr[p] = x
169 | #define ___bpf_fill2(arr, p, x, args...) arr[p] = x; ___bpf_fill1(arr, p + 1, args)
170 | #define ___bpf_fill3(arr, p, x, args...) arr[p] = x; ___bpf_fill2(arr, p + 1, args)
171 | #define ___bpf_fill4(arr, p, x, args...) arr[p] = x; ___bpf_fill3(arr, p + 1, args)
172 | #define ___bpf_fill5(arr, p, x, args...) arr[p] = x; ___bpf_fill4(arr, p + 1, args)
173 | #define ___bpf_fill6(arr, p, x, args...) arr[p] = x; ___bpf_fill5(arr, p + 1, args)
174 | #define ___bpf_fill7(arr, p, x, args...) arr[p] = x; ___bpf_fill6(arr, p + 1, args)
175 | #define ___bpf_fill8(arr, p, x, args...) arr[p] = x; ___bpf_fill7(arr, p + 1, args)
176 | #define ___bpf_fill9(arr, p, x, args...) arr[p] = x; ___bpf_fill8(arr, p + 1, args)
177 | #define ___bpf_fill10(arr, p, x, args...) arr[p] = x; ___bpf_fill9(arr, p + 1, args)
178 | #define ___bpf_fill11(arr, p, x, args...) arr[p] = x; ___bpf_fill10(arr, p + 1, args)
179 | #define ___bpf_fill12(arr, p, x, args...) arr[p] = x; ___bpf_fill11(arr, p + 1, args)
180 | #define ___bpf_fill(arr, args...) \
181 | ___bpf_apply(___bpf_fill, ___bpf_narg(args))(arr, 0, args)
182 |
183 | /*
184 | * BPF_SEQ_PRINTF to wrap bpf_seq_printf to-be-printed values
185 | * in a structure.
186 | */
187 | #define BPF_SEQ_PRINTF(seq, fmt, args...) \
188 | ({ \
189 | static const char ___fmt[] = fmt; \
190 | unsigned long long ___param[___bpf_narg(args)]; \
191 | \
192 | _Pragma("GCC diagnostic push") \
193 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
194 | ___bpf_fill(___param, args); \
195 | _Pragma("GCC diagnostic pop") \
196 | \
197 | bpf_seq_printf(seq, ___fmt, sizeof(___fmt), \
198 | ___param, sizeof(___param)); \
199 | })
200 |
201 | /*
202 | * BPF_SNPRINTF wraps the bpf_snprintf helper with variadic arguments instead of
203 | * an array of u64.
204 | */
205 | #define BPF_SNPRINTF(out, out_size, fmt, args...) \
206 | ({ \
207 | static const char ___fmt[] = fmt; \
208 | unsigned long long ___param[___bpf_narg(args)]; \
209 | \
210 | _Pragma("GCC diagnostic push") \
211 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
212 | ___bpf_fill(___param, args); \
213 | _Pragma("GCC diagnostic pop") \
214 | \
215 | bpf_snprintf(out, out_size, ___fmt, \
216 | ___param, sizeof(___param)); \
217 | })
218 |
219 | #ifdef BPF_NO_GLOBAL_DATA
220 | #define BPF_PRINTK_FMT_MOD
221 | #else
222 | #define BPF_PRINTK_FMT_MOD static const
223 | #endif
224 |
225 | #define __bpf_printk(fmt, ...) \
226 | ({ \
227 | BPF_PRINTK_FMT_MOD char ____fmt[] = fmt; \
228 | bpf_trace_printk(____fmt, sizeof(____fmt), \
229 | ##__VA_ARGS__); \
230 | })
231 |
232 | /*
233 | * __bpf_vprintk wraps the bpf_trace_vprintk helper with variadic arguments
234 | * instead of an array of u64.
235 | */
236 | #define __bpf_vprintk(fmt, args...) \
237 | ({ \
238 | static const char ___fmt[] = fmt; \
239 | unsigned long long ___param[___bpf_narg(args)]; \
240 | \
241 | _Pragma("GCC diagnostic push") \
242 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
243 | ___bpf_fill(___param, args); \
244 | _Pragma("GCC diagnostic pop") \
245 | \
246 | bpf_trace_vprintk(___fmt, sizeof(___fmt), \
247 | ___param, sizeof(___param)); \
248 | })
249 |
250 | /* Use __bpf_printk when bpf_printk call has 3 or fewer fmt args
251 | * Otherwise use __bpf_vprintk
252 | */
253 | #define ___bpf_pick_printk(...) \
254 | ___bpf_nth(_, ##__VA_ARGS__, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
255 | __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, __bpf_vprintk, \
256 | __bpf_vprintk, __bpf_vprintk, __bpf_printk /*3*/, __bpf_printk /*2*/,\
257 | __bpf_printk /*1*/, __bpf_printk /*0*/)
258 |
259 | /* Helper macro to print out debug messages */
260 | #define bpf_printk(fmt, args...) ___bpf_pick_printk(args)(fmt, ##args)
261 |
262 | #endif
263 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/bpf_tracing.h:
--------------------------------------------------------------------------------
1 | /* SPDX-License-Identifier: (LGPL-2.1 OR BSD-2-Clause) */
2 | #ifndef __BPF_TRACING_H__
3 | #define __BPF_TRACING_H__
4 |
5 | /* Scan the ARCH passed in from ARCH env variable (see Makefile) */
6 | #if defined(__TARGET_ARCH_x86)
7 | #define bpf_target_x86
8 | #define bpf_target_defined
9 | #elif defined(__TARGET_ARCH_s390)
10 | #define bpf_target_s390
11 | #define bpf_target_defined
12 | #elif defined(__TARGET_ARCH_arm)
13 | #define bpf_target_arm
14 | #define bpf_target_defined
15 | #elif defined(__TARGET_ARCH_arm64)
16 | #define bpf_target_arm64
17 | #define bpf_target_defined
18 | #elif defined(__TARGET_ARCH_mips)
19 | #define bpf_target_mips
20 | #define bpf_target_defined
21 | #elif defined(__TARGET_ARCH_powerpc)
22 | #define bpf_target_powerpc
23 | #define bpf_target_defined
24 | #elif defined(__TARGET_ARCH_sparc)
25 | #define bpf_target_sparc
26 | #define bpf_target_defined
27 | #elif defined(__TARGET_ARCH_riscv)
28 | #define bpf_target_riscv
29 | #define bpf_target_defined
30 | #else
31 |
32 | /* Fall back to what the compiler says */
33 | #if defined(__x86_64__)
34 | #define bpf_target_x86
35 | #define bpf_target_defined
36 | #elif defined(__s390__)
37 | #define bpf_target_s390
38 | #define bpf_target_defined
39 | #elif defined(__arm__)
40 | #define bpf_target_arm
41 | #define bpf_target_defined
42 | #elif defined(__aarch64__)
43 | #define bpf_target_arm64
44 | #define bpf_target_defined
45 | #elif defined(__mips__)
46 | #define bpf_target_mips
47 | #define bpf_target_defined
48 | #elif defined(__powerpc__)
49 | #define bpf_target_powerpc
50 | #define bpf_target_defined
51 | #elif defined(__sparc__)
52 | #define bpf_target_sparc
53 | #define bpf_target_defined
54 | #elif defined(__riscv) && __riscv_xlen == 64
55 | #define bpf_target_riscv
56 | #define bpf_target_defined
57 | #endif /* no compiler target */
58 |
59 | #endif
60 |
61 | #ifndef __BPF_TARGET_MISSING
62 | #define __BPF_TARGET_MISSING "GCC error \"Must specify a BPF target arch via __TARGET_ARCH_xxx\""
63 | #endif
64 |
65 | #if defined(bpf_target_x86)
66 |
67 | #if defined(__KERNEL__) || defined(__VMLINUX_H__)
68 |
69 | #define PT_REGS_PARM1(x) ((x)->di)
70 | #define PT_REGS_PARM2(x) ((x)->si)
71 | #define PT_REGS_PARM3(x) ((x)->dx)
72 | #define PT_REGS_PARM4(x) ((x)->cx)
73 | #define PT_REGS_PARM5(x) ((x)->r8)
74 | #define PT_REGS_RET(x) ((x)->sp)
75 | #define PT_REGS_FP(x) ((x)->bp)
76 | #define PT_REGS_RC(x) ((x)->ax)
77 | #define PT_REGS_SP(x) ((x)->sp)
78 | #define PT_REGS_IP(x) ((x)->ip)
79 |
80 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), di)
81 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), si)
82 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), dx)
83 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), cx)
84 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), r8)
85 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), sp)
86 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), bp)
87 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), ax)
88 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), sp)
89 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), ip)
90 |
91 | #else
92 |
93 | #ifdef __i386__
94 | /* i386 kernel is built with -mregparm=3 */
95 | #define PT_REGS_PARM1(x) ((x)->eax)
96 | #define PT_REGS_PARM2(x) ((x)->edx)
97 | #define PT_REGS_PARM3(x) ((x)->ecx)
98 | #define PT_REGS_PARM4(x) 0
99 | #define PT_REGS_PARM5(x) 0
100 | #define PT_REGS_RET(x) ((x)->esp)
101 | #define PT_REGS_FP(x) ((x)->ebp)
102 | #define PT_REGS_RC(x) ((x)->eax)
103 | #define PT_REGS_SP(x) ((x)->esp)
104 | #define PT_REGS_IP(x) ((x)->eip)
105 |
106 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), eax)
107 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), edx)
108 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), ecx)
109 | #define PT_REGS_PARM4_CORE(x) 0
110 | #define PT_REGS_PARM5_CORE(x) 0
111 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), esp)
112 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), ebp)
113 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), eax)
114 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), esp)
115 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), eip)
116 |
117 | #else
118 |
119 | #define PT_REGS_PARM1(x) ((x)->rdi)
120 | #define PT_REGS_PARM2(x) ((x)->rsi)
121 | #define PT_REGS_PARM3(x) ((x)->rdx)
122 | #define PT_REGS_PARM4(x) ((x)->rcx)
123 | #define PT_REGS_PARM5(x) ((x)->r8)
124 | #define PT_REGS_RET(x) ((x)->rsp)
125 | #define PT_REGS_FP(x) ((x)->rbp)
126 | #define PT_REGS_RC(x) ((x)->rax)
127 | #define PT_REGS_SP(x) ((x)->rsp)
128 | #define PT_REGS_IP(x) ((x)->rip)
129 |
130 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), rdi)
131 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), rsi)
132 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), rdx)
133 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), rcx)
134 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), r8)
135 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), rsp)
136 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), rbp)
137 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), rax)
138 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), rsp)
139 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), rip)
140 |
141 | #endif
142 | #endif
143 |
144 | #elif defined(bpf_target_s390)
145 |
146 | /* s390 provides user_pt_regs instead of struct pt_regs to userspace */
147 | struct pt_regs;
148 | #define PT_REGS_S390 const volatile user_pt_regs
149 | #define PT_REGS_PARM1(x) (((PT_REGS_S390 *)(x))->gprs[2])
150 | #define PT_REGS_PARM2(x) (((PT_REGS_S390 *)(x))->gprs[3])
151 | #define PT_REGS_PARM3(x) (((PT_REGS_S390 *)(x))->gprs[4])
152 | #define PT_REGS_PARM4(x) (((PT_REGS_S390 *)(x))->gprs[5])
153 | #define PT_REGS_PARM5(x) (((PT_REGS_S390 *)(x))->gprs[6])
154 | #define PT_REGS_RET(x) (((PT_REGS_S390 *)(x))->gprs[14])
155 | /* Works only with CONFIG_FRAME_POINTER */
156 | #define PT_REGS_FP(x) (((PT_REGS_S390 *)(x))->gprs[11])
157 | #define PT_REGS_RC(x) (((PT_REGS_S390 *)(x))->gprs[2])
158 | #define PT_REGS_SP(x) (((PT_REGS_S390 *)(x))->gprs[15])
159 | #define PT_REGS_IP(x) (((PT_REGS_S390 *)(x))->psw.addr)
160 |
161 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[2])
162 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[3])
163 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[4])
164 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[5])
165 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[6])
166 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[14])
167 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[11])
168 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[2])
169 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), gprs[15])
170 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_S390 *)(x), psw.addr)
171 |
172 | #elif defined(bpf_target_arm)
173 |
174 | #define PT_REGS_PARM1(x) ((x)->uregs[0])
175 | #define PT_REGS_PARM2(x) ((x)->uregs[1])
176 | #define PT_REGS_PARM3(x) ((x)->uregs[2])
177 | #define PT_REGS_PARM4(x) ((x)->uregs[3])
178 | #define PT_REGS_PARM5(x) ((x)->uregs[4])
179 | #define PT_REGS_RET(x) ((x)->uregs[14])
180 | #define PT_REGS_FP(x) ((x)->uregs[11]) /* Works only with CONFIG_FRAME_POINTER */
181 | #define PT_REGS_RC(x) ((x)->uregs[0])
182 | #define PT_REGS_SP(x) ((x)->uregs[13])
183 | #define PT_REGS_IP(x) ((x)->uregs[12])
184 |
185 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), uregs[0])
186 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), uregs[1])
187 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), uregs[2])
188 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), uregs[3])
189 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), uregs[4])
190 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), uregs[14])
191 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), uregs[11])
192 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), uregs[0])
193 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), uregs[13])
194 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), uregs[12])
195 |
196 | #elif defined(bpf_target_arm64)
197 |
198 | /* arm64 provides struct user_pt_regs instead of struct pt_regs to userspace */
199 | struct pt_regs;
200 | #define PT_REGS_ARM64 const volatile struct user_pt_regs
201 | #define PT_REGS_PARM1(x) (((PT_REGS_ARM64 *)(x))->regs[0])
202 | #define PT_REGS_PARM2(x) (((PT_REGS_ARM64 *)(x))->regs[1])
203 | #define PT_REGS_PARM3(x) (((PT_REGS_ARM64 *)(x))->regs[2])
204 | #define PT_REGS_PARM4(x) (((PT_REGS_ARM64 *)(x))->regs[3])
205 | #define PT_REGS_PARM5(x) (((PT_REGS_ARM64 *)(x))->regs[4])
206 | #define PT_REGS_RET(x) (((PT_REGS_ARM64 *)(x))->regs[30])
207 | /* Works only with CONFIG_FRAME_POINTER */
208 | #define PT_REGS_FP(x) (((PT_REGS_ARM64 *)(x))->regs[29])
209 | #define PT_REGS_RC(x) (((PT_REGS_ARM64 *)(x))->regs[0])
210 | #define PT_REGS_SP(x) (((PT_REGS_ARM64 *)(x))->sp)
211 | #define PT_REGS_IP(x) (((PT_REGS_ARM64 *)(x))->pc)
212 |
213 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[0])
214 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[1])
215 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[2])
216 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[3])
217 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[4])
218 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[30])
219 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[29])
220 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), regs[0])
221 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), sp)
222 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_ARM64 *)(x), pc)
223 |
224 | #elif defined(bpf_target_mips)
225 |
226 | #define PT_REGS_PARM1(x) ((x)->regs[4])
227 | #define PT_REGS_PARM2(x) ((x)->regs[5])
228 | #define PT_REGS_PARM3(x) ((x)->regs[6])
229 | #define PT_REGS_PARM4(x) ((x)->regs[7])
230 | #define PT_REGS_PARM5(x) ((x)->regs[8])
231 | #define PT_REGS_RET(x) ((x)->regs[31])
232 | #define PT_REGS_FP(x) ((x)->regs[30]) /* Works only with CONFIG_FRAME_POINTER */
233 | #define PT_REGS_RC(x) ((x)->regs[2])
234 | #define PT_REGS_SP(x) ((x)->regs[29])
235 | #define PT_REGS_IP(x) ((x)->cp0_epc)
236 |
237 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), regs[4])
238 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), regs[5])
239 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), regs[6])
240 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), regs[7])
241 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), regs[8])
242 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), regs[31])
243 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((x), regs[30])
244 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), regs[2])
245 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), regs[29])
246 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), cp0_epc)
247 |
248 | #elif defined(bpf_target_powerpc)
249 |
250 | #define PT_REGS_PARM1(x) ((x)->gpr[3])
251 | #define PT_REGS_PARM2(x) ((x)->gpr[4])
252 | #define PT_REGS_PARM3(x) ((x)->gpr[5])
253 | #define PT_REGS_PARM4(x) ((x)->gpr[6])
254 | #define PT_REGS_PARM5(x) ((x)->gpr[7])
255 | #define PT_REGS_RC(x) ((x)->gpr[3])
256 | #define PT_REGS_SP(x) ((x)->sp)
257 | #define PT_REGS_IP(x) ((x)->nip)
258 |
259 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), gpr[3])
260 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), gpr[4])
261 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), gpr[5])
262 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), gpr[6])
263 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), gpr[7])
264 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), gpr[3])
265 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), sp)
266 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), nip)
267 |
268 | #elif defined(bpf_target_sparc)
269 |
270 | #define PT_REGS_PARM1(x) ((x)->u_regs[UREG_I0])
271 | #define PT_REGS_PARM2(x) ((x)->u_regs[UREG_I1])
272 | #define PT_REGS_PARM3(x) ((x)->u_regs[UREG_I2])
273 | #define PT_REGS_PARM4(x) ((x)->u_regs[UREG_I3])
274 | #define PT_REGS_PARM5(x) ((x)->u_regs[UREG_I4])
275 | #define PT_REGS_RET(x) ((x)->u_regs[UREG_I7])
276 | #define PT_REGS_RC(x) ((x)->u_regs[UREG_I0])
277 | #define PT_REGS_SP(x) ((x)->u_regs[UREG_FP])
278 |
279 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I0])
280 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I1])
281 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I2])
282 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I3])
283 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I4])
284 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I7])
285 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((x), u_regs[UREG_I0])
286 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((x), u_regs[UREG_FP])
287 |
288 | /* Should this also be a bpf_target check for the sparc case? */
289 | #if defined(__arch64__)
290 | #define PT_REGS_IP(x) ((x)->tpc)
291 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), tpc)
292 | #else
293 | #define PT_REGS_IP(x) ((x)->pc)
294 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((x), pc)
295 | #endif
296 |
297 | #elif defined(bpf_target_riscv)
298 |
299 | struct pt_regs;
300 | #define PT_REGS_RV const volatile struct user_regs_struct
301 | #define PT_REGS_PARM1(x) (((PT_REGS_RV *)(x))->a0)
302 | #define PT_REGS_PARM2(x) (((PT_REGS_RV *)(x))->a1)
303 | #define PT_REGS_PARM3(x) (((PT_REGS_RV *)(x))->a2)
304 | #define PT_REGS_PARM4(x) (((PT_REGS_RV *)(x))->a3)
305 | #define PT_REGS_PARM5(x) (((PT_REGS_RV *)(x))->a4)
306 | #define PT_REGS_RET(x) (((PT_REGS_RV *)(x))->ra)
307 | #define PT_REGS_FP(x) (((PT_REGS_RV *)(x))->s5)
308 | #define PT_REGS_RC(x) (((PT_REGS_RV *)(x))->a5)
309 | #define PT_REGS_SP(x) (((PT_REGS_RV *)(x))->sp)
310 | #define PT_REGS_IP(x) (((PT_REGS_RV *)(x))->epc)
311 |
312 | #define PT_REGS_PARM1_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a0)
313 | #define PT_REGS_PARM2_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a1)
314 | #define PT_REGS_PARM3_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a2)
315 | #define PT_REGS_PARM4_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a3)
316 | #define PT_REGS_PARM5_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a4)
317 | #define PT_REGS_RET_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), ra)
318 | #define PT_REGS_FP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), fp)
319 | #define PT_REGS_RC_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), a5)
320 | #define PT_REGS_SP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), sp)
321 | #define PT_REGS_IP_CORE(x) BPF_CORE_READ((PT_REGS_RV *)(x), epc)
322 |
323 | #endif
324 |
325 | #if defined(bpf_target_powerpc)
326 | #define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = (ctx)->link; })
327 | #define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
328 | #elif defined(bpf_target_sparc)
329 | #define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ (ip) = PT_REGS_RET(ctx); })
330 | #define BPF_KRETPROBE_READ_RET_IP BPF_KPROBE_READ_RET_IP
331 | #elif defined(bpf_target_defined)
332 | #define BPF_KPROBE_READ_RET_IP(ip, ctx) \
333 | ({ bpf_probe_read_kernel(&(ip), sizeof(ip), (void *)PT_REGS_RET(ctx)); })
334 | #define BPF_KRETPROBE_READ_RET_IP(ip, ctx) \
335 | ({ bpf_probe_read_kernel(&(ip), sizeof(ip), \
336 | (void *)(PT_REGS_FP(ctx) + sizeof(ip))); })
337 | #endif
338 |
339 | #if !defined(bpf_target_defined)
340 |
341 | #define PT_REGS_PARM1(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
342 | #define PT_REGS_PARM2(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
343 | #define PT_REGS_PARM3(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
344 | #define PT_REGS_PARM4(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
345 | #define PT_REGS_PARM5(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
346 | #define PT_REGS_RET(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
347 | #define PT_REGS_FP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
348 | #define PT_REGS_RC(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
349 | #define PT_REGS_SP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
350 | #define PT_REGS_IP(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
351 |
352 | #define PT_REGS_PARM1_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
353 | #define PT_REGS_PARM2_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
354 | #define PT_REGS_PARM3_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
355 | #define PT_REGS_PARM4_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
356 | #define PT_REGS_PARM5_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
357 | #define PT_REGS_RET_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
358 | #define PT_REGS_FP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
359 | #define PT_REGS_RC_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
360 | #define PT_REGS_SP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
361 | #define PT_REGS_IP_CORE(x) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
362 |
363 | #define BPF_KPROBE_READ_RET_IP(ip, ctx) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
364 | #define BPF_KRETPROBE_READ_RET_IP(ip, ctx) ({ _Pragma(__BPF_TARGET_MISSING); 0l; })
365 |
366 | #endif /* !defined(bpf_target_defined) */
367 |
368 | #ifndef ___bpf_concat
369 | #define ___bpf_concat(a, b) a ## b
370 | #endif
371 | #ifndef ___bpf_apply
372 | #define ___bpf_apply(fn, n) ___bpf_concat(fn, n)
373 | #endif
374 | #ifndef ___bpf_nth
375 | #define ___bpf_nth(_, _1, _2, _3, _4, _5, _6, _7, _8, _9, _a, _b, _c, N, ...) N
376 | #endif
377 | #ifndef ___bpf_narg
378 | #define ___bpf_narg(...) \
379 | ___bpf_nth(_, ##__VA_ARGS__, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
380 | #endif
381 |
382 | #define ___bpf_ctx_cast0() ctx
383 | #define ___bpf_ctx_cast1(x) ___bpf_ctx_cast0(), (void *)ctx[0]
384 | #define ___bpf_ctx_cast2(x, args...) ___bpf_ctx_cast1(args), (void *)ctx[1]
385 | #define ___bpf_ctx_cast3(x, args...) ___bpf_ctx_cast2(args), (void *)ctx[2]
386 | #define ___bpf_ctx_cast4(x, args...) ___bpf_ctx_cast3(args), (void *)ctx[3]
387 | #define ___bpf_ctx_cast5(x, args...) ___bpf_ctx_cast4(args), (void *)ctx[4]
388 | #define ___bpf_ctx_cast6(x, args...) ___bpf_ctx_cast5(args), (void *)ctx[5]
389 | #define ___bpf_ctx_cast7(x, args...) ___bpf_ctx_cast6(args), (void *)ctx[6]
390 | #define ___bpf_ctx_cast8(x, args...) ___bpf_ctx_cast7(args), (void *)ctx[7]
391 | #define ___bpf_ctx_cast9(x, args...) ___bpf_ctx_cast8(args), (void *)ctx[8]
392 | #define ___bpf_ctx_cast10(x, args...) ___bpf_ctx_cast9(args), (void *)ctx[9]
393 | #define ___bpf_ctx_cast11(x, args...) ___bpf_ctx_cast10(args), (void *)ctx[10]
394 | #define ___bpf_ctx_cast12(x, args...) ___bpf_ctx_cast11(args), (void *)ctx[11]
395 | #define ___bpf_ctx_cast(args...) \
396 | ___bpf_apply(___bpf_ctx_cast, ___bpf_narg(args))(args)
397 |
398 | /*
399 | * BPF_PROG is a convenience wrapper for generic tp_btf/fentry/fexit and
400 | * similar kinds of BPF programs, that accept input arguments as a single
401 | * pointer to untyped u64 array, where each u64 can actually be a typed
402 | * pointer or integer of different size. Instead of requring user to write
403 | * manual casts and work with array elements by index, BPF_PROG macro
404 | * allows user to declare a list of named and typed input arguments in the
405 | * same syntax as for normal C function. All the casting is hidden and
406 | * performed transparently, while user code can just assume working with
407 | * function arguments of specified type and name.
408 | *
409 | * Original raw context argument is preserved as well as 'ctx' argument.
410 | * This is useful when using BPF helpers that expect original context
411 | * as one of the parameters (e.g., for bpf_perf_event_output()).
412 | */
413 | #define BPF_PROG(name, args...) \
414 | name(unsigned long long *ctx); \
415 | static __attribute__((always_inline)) typeof(name(0)) \
416 | ____##name(unsigned long long *ctx, ##args); \
417 | typeof(name(0)) name(unsigned long long *ctx) \
418 | { \
419 | _Pragma("GCC diagnostic push") \
420 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
421 | return ____##name(___bpf_ctx_cast(args)); \
422 | _Pragma("GCC diagnostic pop") \
423 | } \
424 | static __attribute__((always_inline)) typeof(name(0)) \
425 | ____##name(unsigned long long *ctx, ##args)
426 |
427 | struct pt_regs;
428 |
429 | #define ___bpf_kprobe_args0() ctx
430 | #define ___bpf_kprobe_args1(x) \
431 | ___bpf_kprobe_args0(), (void *)PT_REGS_PARM1(ctx)
432 | #define ___bpf_kprobe_args2(x, args...) \
433 | ___bpf_kprobe_args1(args), (void *)PT_REGS_PARM2(ctx)
434 | #define ___bpf_kprobe_args3(x, args...) \
435 | ___bpf_kprobe_args2(args), (void *)PT_REGS_PARM3(ctx)
436 | #define ___bpf_kprobe_args4(x, args...) \
437 | ___bpf_kprobe_args3(args), (void *)PT_REGS_PARM4(ctx)
438 | #define ___bpf_kprobe_args5(x, args...) \
439 | ___bpf_kprobe_args4(args), (void *)PT_REGS_PARM5(ctx)
440 | #define ___bpf_kprobe_args(args...) \
441 | ___bpf_apply(___bpf_kprobe_args, ___bpf_narg(args))(args)
442 |
443 | /*
444 | * BPF_KPROBE serves the same purpose for kprobes as BPF_PROG for
445 | * tp_btf/fentry/fexit BPF programs. It hides the underlying platform-specific
446 | * low-level way of getting kprobe input arguments from struct pt_regs, and
447 | * provides a familiar typed and named function arguments syntax and
448 | * semantics of accessing kprobe input paremeters.
449 | *
450 | * Original struct pt_regs* context is preserved as 'ctx' argument. This might
451 | * be necessary when using BPF helpers like bpf_perf_event_output().
452 | */
453 | #define BPF_KPROBE(name, args...) \
454 | name(struct pt_regs *ctx); \
455 | static __attribute__((always_inline)) typeof(name(0)) \
456 | ____##name(struct pt_regs *ctx, ##args); \
457 | typeof(name(0)) name(struct pt_regs *ctx) \
458 | { \
459 | _Pragma("GCC diagnostic push") \
460 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
461 | return ____##name(___bpf_kprobe_args(args)); \
462 | _Pragma("GCC diagnostic pop") \
463 | } \
464 | static __attribute__((always_inline)) typeof(name(0)) \
465 | ____##name(struct pt_regs *ctx, ##args)
466 |
467 | #define ___bpf_kretprobe_args0() ctx
468 | #define ___bpf_kretprobe_args1(x) \
469 | ___bpf_kretprobe_args0(), (void *)PT_REGS_RC(ctx)
470 | #define ___bpf_kretprobe_args(args...) \
471 | ___bpf_apply(___bpf_kretprobe_args, ___bpf_narg(args))(args)
472 |
473 | /*
474 | * BPF_KRETPROBE is similar to BPF_KPROBE, except, it only provides optional
475 | * return value (in addition to `struct pt_regs *ctx`), but no input
476 | * arguments, because they will be clobbered by the time probed function
477 | * returns.
478 | */
479 | #define BPF_KRETPROBE(name, args...) \
480 | name(struct pt_regs *ctx); \
481 | static __attribute__((always_inline)) typeof(name(0)) \
482 | ____##name(struct pt_regs *ctx, ##args); \
483 | typeof(name(0)) name(struct pt_regs *ctx) \
484 | { \
485 | _Pragma("GCC diagnostic push") \
486 | _Pragma("GCC diagnostic ignored \"-Wint-conversion\"") \
487 | return ____##name(___bpf_kretprobe_args(args)); \
488 | _Pragma("GCC diagnostic pop") \
489 | } \
490 | static __always_inline typeof(name(0)) ____##name(struct pt_regs *ctx, ##args)
491 |
492 | #endif
493 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/common.h:
--------------------------------------------------------------------------------
1 | // This is a compact version of `vmlinux.h` to be used in the examples using C code.
2 |
3 | #pragma once
4 |
5 | typedef unsigned char __u8;
6 | typedef short int __s16;
7 | typedef short unsigned int __u16;
8 | typedef int __s32;
9 | typedef unsigned int __u32;
10 | typedef long long int __s64;
11 | typedef long long unsigned int __u64;
12 | typedef __u8 u8;
13 | typedef __s16 s16;
14 | typedef __u16 u16;
15 | typedef __s32 s32;
16 | typedef __u32 u32;
17 | typedef __s64 s64;
18 | typedef __u64 u64;
19 | typedef __u16 __le16;
20 | typedef __u16 __be16;
21 | typedef __u32 __be32;
22 | typedef __u64 __be64;
23 | typedef __u32 __wsum;
24 |
25 | #include "bpf_helpers.h"
26 |
27 | enum bpf_map_type {
28 | BPF_MAP_TYPE_UNSPEC = 0,
29 | BPF_MAP_TYPE_HASH = 1,
30 | BPF_MAP_TYPE_ARRAY = 2,
31 | BPF_MAP_TYPE_PROG_ARRAY = 3,
32 | BPF_MAP_TYPE_PERF_EVENT_ARRAY = 4,
33 | BPF_MAP_TYPE_PERCPU_HASH = 5,
34 | BPF_MAP_TYPE_PERCPU_ARRAY = 6,
35 | BPF_MAP_TYPE_STACK_TRACE = 7,
36 | BPF_MAP_TYPE_CGROUP_ARRAY = 8,
37 | BPF_MAP_TYPE_LRU_HASH = 9,
38 | BPF_MAP_TYPE_LRU_PERCPU_HASH = 10,
39 | BPF_MAP_TYPE_LPM_TRIE = 11,
40 | BPF_MAP_TYPE_ARRAY_OF_MAPS = 12,
41 | BPF_MAP_TYPE_HASH_OF_MAPS = 13,
42 | BPF_MAP_TYPE_DEVMAP = 14,
43 | BPF_MAP_TYPE_SOCKMAP = 15,
44 | BPF_MAP_TYPE_CPUMAP = 16,
45 | BPF_MAP_TYPE_XSKMAP = 17,
46 | BPF_MAP_TYPE_SOCKHASH = 18,
47 | BPF_MAP_TYPE_CGROUP_STORAGE = 19,
48 | BPF_MAP_TYPE_REUSEPORT_SOCKARRAY = 20,
49 | BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE = 21,
50 | BPF_MAP_TYPE_QUEUE = 22,
51 | BPF_MAP_TYPE_STACK = 23,
52 | BPF_MAP_TYPE_SK_STORAGE = 24,
53 | BPF_MAP_TYPE_DEVMAP_HASH = 25,
54 | BPF_MAP_TYPE_STRUCT_OPS = 26,
55 | BPF_MAP_TYPE_RINGBUF = 27,
56 | BPF_MAP_TYPE_INODE_STORAGE = 28,
57 | };
58 |
59 | enum xdp_action {
60 | XDP_ABORTED = 0,
61 | XDP_DROP = 1,
62 | XDP_PASS = 2,
63 | XDP_TX = 3,
64 | XDP_REDIRECT = 4,
65 | };
66 |
67 | struct xdp_md {
68 | __u32 data;
69 | __u32 data_end;
70 | __u32 data_meta;
71 | __u32 ingress_ifindex;
72 | __u32 rx_queue_index;
73 | __u32 egress_ifindex;
74 | };
75 |
76 | typedef __u16 __sum16;
77 |
78 | #define ETH_P_IP 0x0800
79 |
80 | struct ethhdr {
81 | unsigned char h_dest[6];
82 | unsigned char h_source[6];
83 | __be16 h_proto;
84 | };
85 |
86 | struct iphdr {
87 | __u8 ihl: 4;
88 | __u8 version: 4;
89 | __u8 tos;
90 | __be16 tot_len;
91 | __be16 id;
92 | __be16 frag_off;
93 | __u8 ttl;
94 | __u8 protocol;
95 | __sum16 check;
96 | __be32 saddr;
97 | __be32 daddr;
98 | };
99 |
100 | enum {
101 | BPF_ANY = 0,
102 | BPF_NOEXIST = 1,
103 | BPF_EXIST = 2,
104 | BPF_F_LOCK = 4,
105 | };
106 |
107 | /* BPF_FUNC_perf_event_output, BPF_FUNC_perf_event_read and
108 | * BPF_FUNC_perf_event_read_value flags.
109 | */
110 | #define BPF_F_INDEX_MASK 0xffffffffULL
111 | #define BPF_F_CURRENT_CPU BPF_F_INDEX_MASK
112 |
113 | #if defined(__TARGET_ARCH_x86)
114 | struct pt_regs {
115 | /*
116 | * C ABI says these regs are callee-preserved. They aren't saved on kernel entry
117 | * unless syscall needs a complete, fully filled "struct pt_regs".
118 | */
119 | unsigned long r15;
120 | unsigned long r14;
121 | unsigned long r13;
122 | unsigned long r12;
123 | unsigned long rbp;
124 | unsigned long rbx;
125 | /* These regs are callee-clobbered. Always saved on kernel entry. */
126 | unsigned long r11;
127 | unsigned long r10;
128 | unsigned long r9;
129 | unsigned long r8;
130 | unsigned long rax;
131 | unsigned long rcx;
132 | unsigned long rdx;
133 | unsigned long rsi;
134 | unsigned long rdi;
135 | /*
136 | * On syscall entry, this is syscall#. On CPU exception, this is error code.
137 | * On hw interrupt, it's IRQ number:
138 | */
139 | unsigned long orig_rax;
140 | /* Return frame for iretq */
141 | unsigned long rip;
142 | unsigned long cs;
143 | unsigned long eflags;
144 | unsigned long rsp;
145 | unsigned long ss;
146 | /* top of stack page */
147 | };
148 | #endif /* __TARGET_ARCH_x86 */
149 |
--------------------------------------------------------------------------------
/pkg/ebpf/src/headers/update.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 |
3 | # Version of libbpf to fetch headers from
4 | LIBBPF_VERSION=0.6.1
5 |
6 | # The headers we want
7 | prefix=libbpf-"$LIBBPF_VERSION"
8 | headers=(
9 | "$prefix"/LICENSE.BSD-2-Clause
10 | "$prefix"/src/bpf_endian.h
11 | "$prefix"/src/bpf_helper_defs.h
12 | "$prefix"/src/bpf_helpers.h
13 | "$prefix"/src/bpf_tracing.h
14 | )
15 |
16 | # Fetch libbpf release and extract the desired headers
17 | curl -sL "https://github.com/libbpf/libbpf/archive/refs/tags/v${LIBBPF_VERSION}.tar.gz" | \
18 | tar -xz --xform='s#.*/##' "${headers[@]}"
19 |
--------------------------------------------------------------------------------
/test/e2e.bats:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bats
2 |
3 | @test "nc to main TCP socket 7777" {
4 | nc -zv 127.0.0.1 7777 &> /dev/null
5 | [ "$?" -eq 0 ]
6 | }
7 |
8 | @test "nc to eBPF sk_lookup 5050" {
9 | nc -zv 127.0.0.1 5050 &> /dev/null
10 | [ "$?" -eq 0 ]
11 | }
12 |
13 | @test "nc to eBPF sk_lookup 6060" {
14 | nc -zv 127.0.0.1 6060 &> /dev/null
15 | [ "$?" -eq 0 ]
16 | }
17 |
18 | @test "nc to eBPF sk_lookup 7070" {
19 | nc -zv 127.0.0.1 7070 &> /dev/null
20 | [ "$?" -eq 0 ]
21 | }
22 |
23 | @test "nc to eBPF sk_lookup 8080" {
24 | nc -zv 127.0.0.1 8080 &> /dev/null
25 | [ "$?" -eq 0 ]
26 | }
27 |
--------------------------------------------------------------------------------
/test/e2e.post:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | ### test pre-flight
4 | echo "> killing nc and sk processes"
5 | killall nc
6 | killall sk
7 |
8 | echo "> removing ebpf leftovers in /sys/fs/bpf/"
9 | rm -rf /sys/fs/bpf/*-nc-test &> /dev/null
10 | sleep 0.5
11 |
--------------------------------------------------------------------------------
/test/e2e.pre:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | echo "> killing nc and sk processes"
4 | killall nc
5 | killall sk
6 |
7 | echo "> removing ebpf leftovers in /sys/fs/bpf/"
8 | rm -rf /sys/fs/bpf/*-nc-test &> /dev/null
9 | sleep 0.5
10 |
11 | echo "> running nc -4kle /bin/cat 127.0.0.1 7777 &"
12 | nc -4kle /bin/cat 127.0.0.1 7777 &
13 | sleep 0.5
14 |
15 | echo "> running bin/sk start --pid $(pidof nc) --ports 5050,6060,7070,8080 --name nc-test --loglevel debug &"
16 | bin/sk start --pid $(pidof nc) --ports 5050,6060,7070,8080 --name nc-test --loglevel debug &
17 | sleep 0.5
18 |
--------------------------------------------------------------------------------