Full Code of quarkslab/peetch for AI

master 2ec684d10368 cached
15 files
70.2 KB
18.7k tokens
42 symbols
1 requests
Download .txt
Repository: quarkslab/peetch
Branch: master
Commit: 2ec684d10368
Files: 15
Total size: 70.2 KB

Directory structure:
gitextract_b_gn6amn/

├── Dockerfile
├── LICENSE.txt
├── README.md
├── doc/
│   └── notes.md
├── peetch/
│   ├── __init__.py
│   ├── __main__.py
│   ├── c_utils/
│   │   └── libssl.c
│   ├── ebpf_programs/
│   │   ├── peetch_kprobes.c
│   │   ├── peetch_proxy.c
│   │   └── peetch_uprobes.c
│   ├── globals.py
│   ├── proxy.py
│   └── utils.py
├── requirements.txt
└── setup.py

================================================
FILE CONTENTS
================================================

================================================
FILE: Dockerfile
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

FROM ubuntu:22.04

ENV TZ=Europe/Paris DEBIAN_FRONTEND=noninteractive
RUN echo 'PS1="quarkslab/peetch:\w# "' >> /root/.bashrc

# Install dependencies
RUN set -x && \
    PACKAGES="bison build-essential cmake flex git \
    libedit-dev libllvm11 llvm-11-dev libclang-11-dev python3 zlib1g-dev \
    libelf-dev libfl-dev python3-distutils python3-pip linux-headers-$(uname -r) \
    libssl-dev iproute2 tmux curl bc libelf-dev zip tshark curl" && \
    apt-get update && apt-get install -y $PACKAGES && \
    apt-get autoclean && apt-get --purge -y autoremove && \
    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*

# Compile bcc
RUN git clone https://github.com/iovisor/bcc && cd bcc/ && mkdir build && \
    cd build && cmake .. && make install && cd src && make install && rm -rf /bcc/

# Install peetch
COPY . /peetch
RUN cd /peetch && pip install --upgrade pip && pip install -r requirements.txt && \
    pip install . && rm -rf /peetch

================================================
FILE: LICENSE.txt
================================================
                    GNU GENERAL PUBLIC LICENSE
                       Version 2, June 1991

 Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
 Everyone is permitted to copy and distribute verbatim copies
 of this license document, but changing it is not allowed.

                            Preamble

  The licenses for most software are designed to take away your
freedom to share and change it.  By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users.  This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it.  (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.)  You can apply it to
your programs, too.

  When we speak of free software, we are referring to freedom, not
price.  Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.

  To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.

  For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have.  You must make sure that they, too, receive or can get the
source code.  And you must show them these terms so they know their
rights.

  We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.

  Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software.  If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.

  Finally, any free program is threatened constantly by software
patents.  We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary.  To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.

  The precise terms and conditions for copying, distribution and
modification follow.

                    GNU GENERAL PUBLIC LICENSE
   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION

  0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License.  The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language.  (Hereinafter, translation is included without limitation in
the term "modification".)  Each licensee is addressed as "you".

Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope.  The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.

  1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.

You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.

  2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:

    a) You must cause the modified files to carry prominent notices
    stating that you changed the files and the date of any change.

    b) You must cause any work that you distribute or publish, that in
    whole or in part contains or is derived from the Program or any
    part thereof, to be licensed as a whole at no charge to all third
    parties under the terms of this License.

    c) If the modified program normally reads commands interactively
    when run, you must cause it, when started running for such
    interactive use in the most ordinary way, to print or display an
    announcement including an appropriate copyright notice and a
    notice that there is no warranty (or else, saying that you provide
    a warranty) and that users may redistribute the program under
    these conditions, and telling the user how to view a copy of this
    License.  (Exception: if the Program itself is interactive but
    does not normally print such an announcement, your work based on
    the Program is not required to print an announcement.)

These requirements apply to the modified work as a whole.  If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works.  But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.

Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.

In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.

  3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:

    a) Accompany it with the complete corresponding machine-readable
    source code, which must be distributed under the terms of Sections
    1 and 2 above on a medium customarily used for software interchange; or,

    b) Accompany it with a written offer, valid for at least three
    years, to give any third party, for a charge no more than your
    cost of physically performing source distribution, a complete
    machine-readable copy of the corresponding source code, to be
    distributed under the terms of Sections 1 and 2 above on a medium
    customarily used for software interchange; or,

    c) Accompany it with the information you received as to the offer
    to distribute corresponding source code.  (This alternative is
    allowed only for noncommercial distribution and only if you
    received the program in object code or executable form with such
    an offer, in accord with Subsection b above.)

The source code for a work means the preferred form of the work for
making modifications to it.  For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable.  However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.

If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.

  4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License.  Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.

  5. You are not required to accept this License, since you have not
signed it.  However, nothing else grants you permission to modify or
distribute the Program or its derivative works.  These actions are
prohibited by law if you do not accept this License.  Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.

  6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions.  You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.

  7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License.  If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all.  For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.

If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.

It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices.  Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.

This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.

  8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded.  In such case, this License incorporates
the limitation as if written in the body of this License.

  9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time.  Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.

Each version is given a distinguishing version number.  If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation.  If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.

  10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission.  For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this.  Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.

                            NO WARRANTY

  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.

  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.

                     END OF TERMS AND CONDITIONS

            How to Apply These Terms to Your New Programs

  If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.

  To do so, attach the following notices to the program.  It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License along
    with this program; if not, write to the Free Software Foundation, Inc.,
    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

Also add information on how to contact you by electronic and paper mail.

If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:

    Gnomovision version 69, Copyright (C) year name of author
    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
    This is free software, and you are welcome to redistribute it
    under certain conditions; type `show c' for details.

The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License.  Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.

You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary.  Here is a sample; alter the names:

  Yoyodyne, Inc., hereby disclaims all copyright interest in the program
  `Gnomovision' (which makes passes at compilers) written by James Hacker.

  <signature of Ty Coon>, 1 April 1989
  Ty Coon, President of Vice

This General Public License does not permit incorporating your program into
proprietary programs.  If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library.  If this is what you want to do, use the GNU Lesser General
Public License instead of this License.


================================================
FILE: README.md
================================================
# peetch

`peetch` is a collection of tools aimed at experimenting with different aspects of eBPF to bypass TLS protocol protections.

Currently, peetch includes three subcommands. The first called `dump` aims to sniff network traffic by associating information about the source process with each packet. The second called `tls` allows identifying processes using OpenSSL to extract cryptographic keys. The third one `proxy` automatically intercepts TLS traffic from processes using OpenSSL and decrypts messages on the fly.

Combined, the first two commands make it possible to decrypt TLS exchanges recorded in the PCAPng format.

## Installation

`peetch` relies on several dependencies including [bcc](https://github.com/iovisor/bcc) and [Scapy](https://github.com/secdev/scapy). A Docker image can be easily built in order to easily test `peetch` using the following command:

```shell
docker build -t quarkslab/peetch .
```

## Commands Walk Through

The following examples assume that you used the following command to enter the Docker image and launch examples within it:

```shell
docker run --privileged --network host --mount type=bind,source=/sys,target=/sys --mount type=bind,source=/proc,target=/proc --pid host --rm -it quarkslab/peetch
```

### `dump`

This sub-command gives you the ability to sniff packets using an eBPF TC classifier and to retrieve the corresponding PID and process names with:

```shell
peetch dump
curl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https S / Padding
curl/1289291 - Ether / IP / TCP 208.97.177.124:https > 10.211.55.10:53052 SA / Padding
curl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https A / Padding
curl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https PA / Raw / Padding
curl/1289291 - Ether / IP / TCP 208.97.177.124:https > 10.211.55.10:53052 A / Padding
```

Note that as of today, `dump` will only capture IPv4 based TCP segments.

For convenience, the captured packets can be store to PCAPng along with process information using `--write`:

```shell
peetch dump --write peetch.pcapng
^C
```

This PCAPng can easily be manipulated with Wireshark or Scapy:

```python
scapy
>>> l = rdpcap("peetch.pcapng")
>>> l[0]
<Ether  dst=00:1c:42:00:00:18 src=00:1c:42:54:f3:34 type=IPv4 |<IP  version=4 ihl=5 tos=0x0 len=60 id=11088 flags=DF frag=0 ttl=64 proto=tcp chksum=0x4bb1 src=10.211.55.10 dst=208.97.177.124 |<TCP  sport=53054 dport=https seq=631406526 ack=0 dataofs=10 reserved=0 flags=S window=64240 chksum=0xc3e9 urgptr=0 options=[('MSS', 1460), ('SAckOK', b''), ('Timestamp', (1272423534, 0)), ('NOP', None), ('WScale', 7)] |<Padding  load='\x00\x00' |>>>>
>>> l[0].comment
b'curl/1289909'
```

### `tls`

This sub-command aims to identify processes that uses OpenSSL and makes it easy to dump several things like plaintext and secrets.

By default, `peetch tls` will only display one line per process, the `--directions` argument makes it possible to display the exchanged messages:

```shell
peetch tls --directions
<- curl (1291078) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256
-> curl (1291078) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256
```

Displaying OpenSSL buffer content is achieved with `--content`.

```shell
peetch tls --content
<- curl (1290608) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256

   0000  47 45 54 20 2F 20 48 54 54 50 2F 31 2E 31 0D 0A  GET / HTTP/1.1..
   0010  48 6F 73 74 3A 20 77 77 77 2E 70 65 72 64 75 2E  Host: www.perdu.
   0020  63 6F 6D 0D 0A 55 73 65 72 2D 41 67 65 6E 74 3A  com..User-Agent:
   0030  20 63 75 72 6C 2F 37 2E 36 38 2E 30 0D 0A 41 63   curl/7.68.0..Ac

-> curl (1290608) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256

   0000  48 54 54 50 2F 31 2E 31 20 32 30 30 20 4F 4B 0D  HTTP/1.1 200 OK.
   0010  0A 44 61 74 65 3A 20 54 68 75 2C 20 31 39 20 4D  .Date: Thu, 19 M
   0020  61 79 20 32 30 32 32 20 31 38 3A 31 36 3A 30 31  ay 2022 18:16:01
   0030  20 47 4D 54 0D 0A 53 65 72 76 65 72 3A 20 41 70   GMT..Server: Ap
```

The `--secrets` arguments will display TLS Master Secrets extracted from memory. The following example leverages `--write` to write master secrets to simplify decrypting TLS messages with Scapy:

```shell
(sleep 5; curl https://www.perdu.com/?name=highly%20secret%20information --tls-max 1.2 --http1.1 --tlsv1.2) &

peetch tls --write &
curl (1293232) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256

peetch dump --write traffic.pcapng
^C

# Add the master secret to a PCAPng file
editcap --inject-secrets tls,1293232-master_secret.log traffic.pcapng traffic-ms.pcapng

scapy
>>> load_layer("tls")
>>> conf.tls_session_enable = True
>>> l = rdpcap("traffic-ms.pcapng")
>>> l[13][TLS].msg
[<TLSApplicationData  data='GET /?name=highly%20secret%20information HTTP/1.1\r\nHost: www.perdu.com\r\nUser-Agent: curl/7.68.0\r\nAccept: */*\r\n\r\n' |>]
```

### `proxy`

This sub-command uses eBPF programs to automatically intercept TLS traffic from processes using OpenSSL and decrypt messages on the fly using Scapy.

In the following example, `peetch proxy` display a secret value sent to a server by the `openssl` process.

```shell
peetch proxy
[-] Proxying OpenSSL traffic
[+] Intercepting traffic from openssl/451255 to 172.67.133.176/443 via 127.0.0.1/58039
    --> 127.0.0.1:58039 > 172.67.133.176:https tcp
    <-- 172.67.133.176:https > 127.0.0.1:58039 tcp
    --> 127.0.0.1:58039 > 172.67.133.176:https tcp
    <-- 172.67.133.176:https > 127.0.0.1:58039 tcp
    --> 127.0.0.1:58039 > 172.67.133.176:https tcp
    --> 127.0.0.1:58039 > 172.67.133.176:https tcp

###[ TLS Application Data ]###
  data      = b'GET /?secret=9590 HTTP/1.1\r\nHost: www.perdu.com\r\n\r\n\n'
```

## Limitations

By design, `peetch` only supports OpenSSL, IPv4 and TLS 1.2.


================================================
FILE: doc/notes.md
================================================
# Notes

This document contains various information used to debug and test `peetch` features.

# Tests

* `openssl s_client`
```
rm secrets.txt ; (sleep 1 ;echo -e "GET /?secret=$RANDOM HTTP/1.1\r\nHost: www.perdu.com\r\n\r\n") |openssl s_client -connect www.perdu.com:443 -keylogfile secrets.txt -no_tls1_3 -4; cat secrets.txt
```

* test the connectin to the proxy
```
curl --connect-to www.perdu.com:443:127.0.0.1:2807 https://www.perdu.com
```

* libcurl binaries
```
# TLS1.2 & HTTP/1.1
curl https://echo.free.beeceptor.com/?secret_number=$RANDOM --tls-max 1.2 --http1.1 --tlsv1.2 --libcurl secret_binary.c
cc -o secret_binary secret_binary.c -lssl -lcurl && ./secret_binary

# TLS1.2 & HTTP/2.0
curl https://echo.free.beeceptor.com/?secret_number=$RANDOM --tls-max 1.2 --http2 --tlsv1.2 --libcurl secret_binary2.c
cc -o secret_binary2 secret_binary2.c -lssl -lcurl && ./secret_binary2
```

# OpenSSL Offsets

The following radare2 commands could be used to validate the OpenSSL offsets dynamically generated by `peetch`:

```
cat curl.rr2
#!/usr/bin/rarun2
program=/usr/bin/curl
arg0=5
arg1=--tls-max
arg2=1.2
arg3=--tlsv1.2
arg4=--http1.1
arg5=https://www.perdu.com

radare2 -e dbg.profile=curl.rr2 -A -d /usr/bin/curl
[...]> dcu sym.imp.curl_globa_init
[...]> dmi libssl SSL_read
[...]> dmi libssl SSL_write
[...]> db 0xffffa479eeb4 # address of SSL_read
[...]> db 0xffff9086f504 # address of SSL_write
[...]> dc

[...]> px 48 @ `pv @ x0 + 0x918` + 0x50 # offset off ssl_session and master_secret
- offset - 6061 6263 6465 6667 6869 6A6B 6C6D 6E6F 0123456789ABCDEF
0xaaab0a47aa60 ce6a 7675 5e95 dfd4 e5ed 10c1 c0b7 9bd9 .jvu^...........
0xaaab0a47aa70 808f 416a 13ef cb29 6c8e 323a 40cb e5ea ..Aj...)l.2:@...
0xaaab0a47aa80 ccdb 09d2 7f46 7fb9 7115 6082 f4dc 2725 .....F..q.`...'%
```
```

================================================
FILE: peetch/__init__.py
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

import argparse
import asyncio
import atexit
import ctypes as ct
import binascii
import os
import socket
import struct
import sys
import time

from bcc import BPF, BPFProgType, BPFAttachType
import pyroute2
from scapy.all import Ether, wrpcapng, hexdump, load_layer, conf

import peetch.globals
from peetch.proxy import all_tasks
import peetch.utils


load_layer("tls")
conf.tls_session_enable = True

global BPF_HANDLER, BPF_TLS_HANDLER

EBPF_PROGRAMS_DIRNAME = os.path.join(os.path.dirname(__file__),
                                     "ebpf_programs/")
BPF_DUMP_PROGRAM_FILENAME = "%s/peetch_kprobes.c" % EBPF_PROGRAMS_DIRNAME
BPF_DUMP_PROGRAM_SOURCE = open(BPF_DUMP_PROGRAM_FILENAME).read()
BPF_TLS_PROGRAM_FILENAME = "%s/peetch_uprobes.c" % EBPF_PROGRAMS_DIRNAME
BPF_TLS_PROGRAM_SOURCE = open(BPF_TLS_PROGRAM_FILENAME).read()
BPF_PROXY_PROGRAM_FILENAME = "%s/peetch_proxy.c" % EBPF_PROGRAMS_DIRNAME
BPF_PROXY_PROGRAM_SOURCE = open(BPF_PROXY_PROGRAM_FILENAME).read()
PACKETS_CAPTURED = []
TLS_INFORMATION = {}


def load_classifier(interface, ebpf_function):
    """
    Load an eBPF TC Classifier
    """
    iproute_handler = pyroute2.IPRoute()

    ip_link = iproute_handler.link_lookup(ifname=interface)
    if not ip_link:
        sys.exit()

    ip_link = ip_link[0]
    iproute_handler.tc("add", "clsact", ip_link)

    # add ingress clsact
    iproute_handler.tc("add-filter", "bpf", ip_link, ":1",
                       fd=ebpf_function.fd, name=ebpf_function.name,
                       parent="ffff:fff2")

    # add egress clsact
    iproute_handler.tc("add-filter", "bpf", ip_link, ":1",
                       fd=ebpf_function.fd, name=ebpf_function.name,
                       parent="ffff:fff3")


def unload_classifier(interface):
    """
    Unload an eBPF TC Classifier
    """
    os.system("tc qdisc del dev %s clsact" % args.interface)


def exit_handler_command(interface, filename, bpf_handler):
    """
    Exit command nicely
    """
    time.sleep(0.01)
    bpf_handler.detach_kprobe(event="security_sk_classify_flow",
                              fn_name="kprobe_security_sk_classify_flow")
    unload_classifier(interface)
    if filename:
        wrpcapng(filename, PACKETS_CAPTURED)


def exit_handler_proxy(bpf_handler, connect_function, cgroup_fd):
    """
    Exit proxy nicely
    """
    time.sleep(0.01)
    bpf_handler.detach_func(connect_function, cgroup_fd,
                            BPFAttachType.CGROUP_INET4_CONNECT)
    if cgroup_fd > 0:
        os.close(cgroup_fd)


def handle_skb_event(cpu, data, size):
    """
    Handle SKB events from the kernel
    """

    # Structure retrieved from the kernel
    class SkbEvent(ct.Structure):
        _fields_ = [("pid", ct.c_uint32),
                    ("raw", ct.c_ubyte * (size - ct.sizeof(ct.c_uint32)))]

    # Map the data from kernel to the structure
    skb_event = ct.cast(data, ct.POINTER(SkbEvent)).contents
    data = bytes(skb_event.raw)

    # Extract the process name
    for i in range(len(data)):
        if data[i] == 0:
            break
    process_name = data[:i].decode("utf-8", "replace")
    data = data[16:]

    process_information = "%s/%d" % (process_name, skb_event.pid)

    # Parse the packet with Scapy
    pkt = Ether(data)

    if args.write:
        pkt.comment = str(process_information)
        PACKETS_CAPTURED.append(pkt)
    else:
        if not args.raw:
            print(process_information, end=" - ")
        print(pkt.summary())


def dump_command(args):
    # Compile eBPF programs
    bpf_handler = BPF(text=BPF_DUMP_PROGRAM_SOURCE)

    # Attach the kprobe
    bpf_handler.attach_kprobe(event="security_sk_classify_flow",
                              fn_name="kprobe_security_sk_classify_flow")

    # Setup the exit handler
    atexit.register(exit_handler_command, args.interface, args.write,
                    bpf_handler)

    # Load eBPF TC Classifier
    classifier_function = bpf_handler.load_func("process_frame", BPF.SCHED_CLS)
    load_classifier(args.interface, classifier_function)

    # Handle incoming skb events
    bpf_handler["skb_events"].open_perf_buffer(handle_skb_event)
    try:
        while True:
            bpf_handler.perf_buffer_poll()
    except KeyboardInterrupt:
        pass


def handle_tls_event(cpu, data, size):
    class TLSEvent(ct.Structure):
        _fields_ = [("address", ct.c_uint32),
                    ("port", ct.c_uint16),
                    ("tls_version", ct.c_uint16),
                    ("comm", ct.c_char * 64),
                    ("message", ct.c_uint8 * 64),
                    ("message_length", ct.c_uint32),
                    ("pid", ct.c_uint32),
                    ("is_read", ct.c_uint32)]

    # Map the data from kernel to the structure
    tls_event = ct.cast(data, ct.POINTER(TLSEvent)).contents

    # Get TLS information
    pid_to_delete = None
    master_secret = None
    ciphersuite = None
    bpf_map_tls_information = BPF_TLS_HANDLER["tls_information_cache"]
    for pid, tls_info in bpf_map_tls_information.items_lookup_batch():
        if pid.value == tls_event.pid:
            ciphersuite = tls_info.ciphersuite.decode("ascii", "ignore")
            master_secret = binascii.hexlify(tls_info.master_secret)
            master_secret = master_secret.decode("ascii", "ignore")
            pid_to_delete = [pid]
            break

    # Delete pid from the eBPF map
    if not pid_to_delete:
        bpf_map_tls_information.items_delete_batch(pid_to_delete)

    # Unpack the IPv4 destination address
    addr = struct.pack("I", tls_event.address)

    # Discard empty content
    if args.content and tls_event.message_length == 0:
        return

    # Display the TLS event
    if args.directions:
        if tls_event.is_read:
            print("->", end=" ")
        else:
            print("<-", end=" ")
    print("%s (%d)" % (tls_event.comm.decode("ascii", "replace"),
                       tls_event.pid), end=" ")
    print("%s/%d" % (socket.inet_ntop(socket.AF_INET, addr),
                     socket.ntohs(tls_event.port)), end=" ")

    version = (tls_event.tls_version & 0xF) - 1
    print("TLS1.%d %s" % (version, ciphersuite))

    # Display TLS secrets
    if (args.secrets or args.write) and tls_event.tls_version == 0x303:
        key_log = "CLIENT_RANDOM 28071980 %s\n" % master_secret
        if args.secrets:
            print("\n   %s\n" % key_log)
        if args.write:
            fd = open("%d-master_secret.log" % pid.value, "w")
            fd.write(key_log)
            fd.close()

    # Display the message content in hexadecimal
    if args.content and tls_event.message_length:
        hex_message = hexdump(tls_event.message[:tls_event.message_length],
                              dump=True)
        print("\n   ", end="")
        print(hex_message.replace("\n", "\n   "))
        print()


def _tls_ebpf_programs(directions_bool, args_ssl_session_offset,
                       args_ssl_cipher_offset, args_master_secret_offset,
                       args_client_hello_offset, args_client_random_offset):
    # Get SSL structures offsets
    offsets = [str(offset) for offset in peetch.utils.get_offsets()]
    ssl_session_offset, ssl_cipher_offset, master_secret_offset, \
        client_hello_offset, client_random_offset = offsets

    if ssl_session_offset == ssl_cipher_offset and \
       ssl_cipher_offset == master_secret_offset and master_secret_offset == '0':  # noqa: E501
        return None

    if args_ssl_session_offset is not None:
        ssl_session_offset = str(args_ssl_session_offset)

    if args_ssl_cipher_offset is not None:
        ssl_cipher_offset = str(args_ssl_cipher_offset)

    if args_master_secret_offset is not None:
        master_secret_offset = str(args_master_secret_offset)

    if args_client_hello_offset is not None:
        client_hello_offset = str(args.client_hello_offset)

    if args_client_random_offset is not None:
        client_random_offset = str(args.client_random_offset)

    # Compile eBPF programs
    ebpf_programs = BPF_TLS_PROGRAM_SOURCE.replace("DIRECTIONS",
                                                   directions_bool)
    ebpf_programs = ebpf_programs.replace("SSL_SESSION_OFFSET",
                                          ssl_session_offset)
    ebpf_programs = ebpf_programs.replace("MASTER_SECRET_OFFSET",
                                          master_secret_offset)
    ebpf_programs = ebpf_programs.replace("SSL_CIPHER_OFFSET",
                                          ssl_cipher_offset)
    ebpf_programs = ebpf_programs.replace("CLIENT_HELLO_OFFSET",
                                          client_hello_offset)
    ebpf_programs = ebpf_programs.replace("CLIENT_RANDOM_OFFSET",
                                          client_random_offset)

    return ebpf_programs


def tls_command(args):
    global BPF_TLS_HANDLER

    # Process arguments
    if args.content:
        args.directions = True

    directions_bool = "1"
    if args.directions:
        directions_bool = "0"

    ebpf_programs = _tls_ebpf_programs(directions_bool,
                                       args.ssl_session_offset,
                                       args.ssl_cipher_offset,
                                       args.master_secret_offset,
                                       args.client_hello_offset,
                                       args.client_random_offset)
    if ebpf_programs is None:
        print("ERROR: cannot guess SSL offsets!", file=sys.stderr)
        sys.exit(1)
    bpf_handler = BPF(text=ebpf_programs)
    BPF_TLS_HANDLER = bpf_handler

    # Attach the probes
    try:
        bpf_handler.attach_uprobe(name="ssl",
                                  sym="SSL_write", fn_name="SSL_write")
        bpf_handler.attach_uprobe(name="ssl",
                                  sym="SSL_read", fn_name="SSL_read")
        bpf_handler.attach_uretprobe(name="ssl",
                                     sym="SSL_read", fn_name="SSL_read_ret")
    except Exception:
        print("tls - cannot attach to eBPF probes!")
        sys.exit()

    def handle_tls_event(cpu, data, size):
        class TLSEvent(ct.Structure):
            _fields_ = [("address", ct.c_uint32),
                        ("port", ct.c_uint16),
                        ("tls_version", ct.c_uint16),
                        ("comm", ct.c_char * 64),
                        ("message", ct.c_uint8 * 64),
                        ("message_length", ct.c_uint32),
                        ("pid", ct.c_uint32),
                        ("is_read", ct.c_uint32)]

        # Map the data from kernel to the structure
        tls_event = ct.cast(data, ct.POINTER(TLSEvent)).contents

        # Get TLS information
        pid_to_delete = None
        master_secret = None
        ciphersuite = None
        client_random = None
        bpf_map_tls_information = bpf_handler["tls_information_cache"]
        for pid, tls_info in bpf_map_tls_information.items_lookup_batch():
            if pid.value == tls_event.pid:
                ciphersuite = tls_info.ciphersuite.decode("ascii", "ignore")
                master_secret = binascii.hexlify(tls_info.master_secret)
                master_secret = master_secret.decode("ascii", "ignore")
                client_random = binascii.hexlify(tls_info.client_random)
                client_random = client_random.decode("ascii", "ignore")
                pid_to_delete = [pid]
                break

        # Delete pid from the eBPF map
        if not pid_to_delete:
            bpf_map_tls_information.items_delete_batch(pid_to_delete)

        # Unpack the IPv4 destination address
        addr = struct.pack("I", tls_event.address)

        # Discard empty content
        if args.content and tls_event.message_length == 0:
            return

        # Display the TLS event
        if args.directions:
            if tls_event.is_read:
                print("->", end=" ")
            else:
                print("<-", end=" ")
        print("%s (%d)" % (tls_event.comm.decode("ascii", "replace"),
                           tls_event.pid), end=" ")
        print("%s/%d" % (socket.inet_ntop(socket.AF_INET, addr),
                         socket.ntohs(tls_event.port)), end=" ")

        version = (tls_event.tls_version & 0xF) - 1
        print("TLS1.%d %s" % (version, ciphersuite))

        # Display TLS secrets
        if (args.secrets or args.write) and tls_event.tls_version == 0x303:
            key_log = "CLIENT_RANDOM %s %s\n" % (client_random, master_secret)
            if args.secrets:
                print("\n   %s\n" % key_log)
            if args.write:
                fd = open("%d-master_secret.log" % pid.value, "w")
                fd.write(key_log)
                fd.close()

        # Display the message content in hexadecimal
        if args.content and tls_event.message_length:
            hex_message = hexdump(tls_event.message[:tls_event.message_length],
                                  dump=True)
            print("\n   ", end="")
            print(hex_message.replace("\n", "\n   "))
            print()

    bpf_handler["tls_events"].open_perf_buffer(handle_tls_event)
    while True:
        try:
            bpf_handler.perf_buffer_poll()
        except KeyboardInterrupt:
            sys.exit()


def proxy_command(args):
    # Compile eBPF programs
    ebpf_programs = BPF_PROXY_PROGRAM_SOURCE.replace("PEETCH_PROXY_PID",
                                                     str(os.getpid()))
    bpf_handler = BPF(text=ebpf_programs)
    peetch.globals.BPF_HANDLER = bpf_handler

    # Load the eBPF function
    connect_function = bpf_handler.load_func("connect_v4_prog",
                                             prog_type=BPFProgType.CGROUP_SOCK_ADDR,  # noqa: E501
                                             attach_type=BPFAttachType.CGROUP_INET4_CONNECT)  # noqa: E501

    # Attach the eBPF function to the default cgroup
    cgroup_fd = os.open("/sys/fs/cgroup", os.O_RDONLY)
    bpf_handler.attach_func(connect_function, cgroup_fd,
                            BPFAttachType.CGROUP_INET4_CONNECT)

    # Attach the SSL_* uprobes
    ebpf_programs = _tls_ebpf_programs("1", None, None, None, None, None)
    if ebpf_programs is None:
        print("ERROR: cannot guess SSL offsets!", file=sys.stderr)
        sys.exit(1)

    bpf_tls_handler = BPF(text=ebpf_programs)
    peetch.globals.BPF_TLS_HANDLER = bpf_tls_handler
    try:
        bpf_tls_handler.attach_uprobe(name="ssl",
                                      sym="SSL_write", fn_name="SSL_write")
        bpf_tls_handler.attach_uprobe(name="ssl",
                                      sym="SSL_read", fn_name="SSL_read")
        bpf_tls_handler.attach_uretprobe(name="ssl",
                                         sym="SSL_read", fn_name="SSL_read_ret")  # noqa: E501
    except Exception:
        print("proxy - cannot attach to eBPF SSL_* uprobes!")
        sys.exit()

    print("[-] Proxying OpenSSL traffic")

    # Setup the exit handler
    atexit.register(exit_handler_proxy, bpf_handler,
                    connect_function, cgroup_fd)

    # Start the proxy
    try:
        asyncio.run(all_tasks(args.debug))
    except KeyboardInterrupt:
        pass


def main():
    global args
    argv = sys.argv[1:]

    # Parsing arguments
    parser = argparse.ArgumentParser(description="peetch - an eBPF playground")
    subparser = parser.add_subparsers()
    parser.set_defaults(func=lambda args: parser.print_help())

    # Prepare the 'dump' subcommand
    dump_parser = subparser.add_parser("dump",
                                       help="Sniff packets with eBPF")
    dump_parser.add_argument("--raw", action="store_true",
                             help="display packets only")
    dump_parser.add_argument("--write", type=str,
                             help="pcapng filename")
    dump_parser.add_argument("--interface", type=str,
                             help="interface name", default=str(conf.iface))
    dump_parser.set_defaults(func=dump_command)

    # Prepare the 'tls' subcommand
    tls_parser = subparser.add_parser("tls",
                                      help="Identify processes that uses TLS")
    tls_parser.add_argument("--directions", action="store_true",
                            help="display read & write calls")
    tls_parser.add_argument("--content", action="store_true",
                            help="display buffers content")
    tls_parser.add_argument("--secrets", action="store_true",
                            help="display TLS secrets")
    tls_parser.add_argument("--write", action="store_true",
                            help="write TLS secrets to files")
    tls_parser.add_argument("--ssl_session_offset",
                            help="offset to the ssl_session_t structure")
    tls_parser.add_argument("--master_secret_offset",
                            help="offset to the master secret in an ssl_session_t structure")  # noqa: E501
    tls_parser.add_argument("--ssl_cipher_offset",
                            help="offset to the ssl_cipher structure in an ssl_session_t structure")  # noqa: E501
    tls_parser.add_argument("--client_hello_offset",
                            help="offset to the CLIENTHELLO_MSG structure in an ssl structure")  # noqa: E501
    tls_parser.add_argument("--client_random_offset",
                            help="offset to the client random in an CLIENTHELLO_MSG structure")  # noqa: E501
    tls_parser.set_defaults(func=tls_command)

    # Prepare the 'proxy' subcommand
    proxy_parser = subparser.add_parser("proxy",
                                        help="Automatically intercept TLS connections")  # noqa: E501
    proxy_parser.add_argument("--debug", action="store_true",
                              help="display debug information")
    proxy_parser.set_defaults(func=proxy_command)

    # Print the Help message when no arguments are provided
    if not argv:
        parser.print_help(sys.stderr)
        sys.exit(1)

    # Call the sub-command
    args = parser.parse_args(argv)
    args.func(args)


================================================
FILE: peetch/__main__.py
================================================
#!/usr/bin/env python3
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

from . import main

main()


================================================
FILE: peetch/c_utils/libssl.c
================================================
// SPDX-License-Identifier: GPL-2.0+
// Guillaume Valadon <gvaladon@quarkslab.com>

#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/socket.h>

#include <openssl/ssl.h>

#define STRUCTURE_SIZE 8192

struct libssl_offsets_t {
  uint64_t ssl_session;
  uint64_t ssl_cipher;
  uint64_t master_secret;
  uint64_t client_hello;
  uint64_t client_random;
};


struct libssl_offsets_t libssl_offsets(char *ip4_address, uint16_t port) {
  struct libssl_offsets_t offsets = { .ssl_session = 0,
                                      .ssl_cipher = 0, .master_secret = 0};

  // Create the SSL context and set the TLS version
  const SSL_METHOD *method = TLS_client_method();
  SSL_CTX *ctx = SSL_CTX_new(method);

  int ret = SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);
  if (ret < 0) {
    printf("SSL_CTX_set_max_proto_version() error - %d\n", ret);
    return offsets;
  }

  // Set up a TLS connection to get the SSL session structure
  SSL *ssl = SSL_new(ctx);

  int fd = socket(AF_INET, SOCK_STREAM, 0);
  if (fd < 0) {
    printf("socket() error - %d\n", fd);
    return offsets;
  }

  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons(port);
  ret = inet_aton(ip4_address, (struct in_addr*) &addr.sin_addr.s_addr);
  if (ret < 0) {
    printf("inet_aton() error - %d\n", fd);
    return offsets;
  }

  ret = connect(fd, (struct sockaddr*) &addr, sizeof(addr));
  if (ret < 0) {
    printf("connect() error - %d\n", fd);
    return offsets;
  }

  ret = SSL_set_fd(ssl, fd);
  if (ret < 0) {
    printf("SSL_set_fd() error - %d\n", fd);
    return offsets;
  }

  ret = SSL_connect(ssl);
  if (ret < 0) {
    printf("SSL_connect() error - %d\n", fd);
    return offsets;
  }

  // SSL_SESSION* offset
  SSL_SESSION *session = SSL_get_session(ssl);
  for (uint64_t i = 0x000; i < STRUCTURE_SIZE; i++) {
    uint64_t value = (uint64_t) ssl + i;
    uint64_t *ptr = (uint64_t*) value;
    if ((uint64_t) *ptr == (uint64_t) session) {
      offsets.ssl_session = i;
      break;
    }
  }

  // SSL_CIPHER* offset
  const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);
  for (uint64_t i = 0x000; i < STRUCTURE_SIZE; i++) {
    uint64_t value = (uint64_t) session + i;
    uint64_t *ptr = (uint64_t*) value;
    if ((uint64_t) *ptr == (uint64_t) cipher) {
      offsets.ssl_cipher = i;
      break;
    }
  }

  // TLS 1.2 MASTER_SECRET offset
  uint8_t master_secret[48];
  ret = SSL_SESSION_get_master_key(session,
                                  (unsigned char*)&master_secret, sizeof(master_secret));
  if (ret != 48) {
    printf("SSL_SESSION_get_master_key() error - %d\n", fd);
    return offsets;
  }
  for (uint64_t i=0x000; i < STRUCTURE_SIZE; i++) {
    uint64_t value = (uint64_t) session + i;
    uint64_t *ptr = (uint64_t*) value;
    value = (uint64_t) session + i + 47;
    uint64_t *ptr_end = (uint64_t*) value;
    if ((*ptr & 0xFF) == master_secret[0] && \
        (*ptr_end & 0xFF) == master_secret[47]) {
      offsets.master_secret = i;
      break;
    }
  }

  // Client Random offset
  uint8_t client_random[32];
  offsets.client_hello = 0;
  ret = SSL_get_client_random(ssl, (unsigned char*)&client_random, sizeof(client_random));
  if (ret != 32) {
    printf("SSL_get_client_random() error - %d\n", fd);
    return offsets;
  }
  for (uint64_t i=0; i < STRUCTURE_SIZE; i++) {
    if (offsets.client_hello != 0)
      break;

    uint64_t value = (uint64_t) ssl + i;
    uint64_t *ptr = (uint64_t*) value;

    if (*ptr) {
      for (uint8_t j=0; j < sizeof(STRUCTURE_SIZE) ; j++) {
          uint8_t *new_ptr = (uint8_t*) ptr + j;
          if ((new_ptr[0] & 0xFF) == client_random[0] && \
              (new_ptr[31] & 0xFF) == client_random[31]) {
            offsets.client_hello = i;
            offsets.client_random = j;
            break;
          }
      }
    }

  }

  return offsets;
}


int main() {
 /*
 Compile it with:
 cc -o libssl_offsets libssl.c -lssl
 */
  struct libssl_offsets_t offsets = libssl_offsets("1.1.1.1", 443);
  printf("--ssl_session_offset=0x%lx\n", offsets.ssl_session);
  printf("--ssl_cipher_offset=0x%lx\n", offsets.ssl_cipher);
  printf("--master_secret_offset=0x%lx\n", offsets.master_secret);
  printf("--client_hello=0x%lx\n", offsets.client_hello);
  printf("--client_random=0x%lx\n", offsets.client_random);

  return EXIT_SUCCESS;
}


================================================
FILE: peetch/ebpf_programs/peetch_kprobes.c
================================================
// SPDX-License-Identifier: GPL-2.0+
// Guillaume Valadon <gvaladon@quarkslab.com>

#include <linux/if_ether.h>
#include <linux/ip.h>
#include <linux/tcp.h>


#include <uapi/linux/pkt_cls.h>
#include <uapi/linux/bpf.h>
#include <linux/sched.h>
#include <net/sock.h>


struct key_t {
  u32 dst;
  u32 src;
};

struct data_t {
  u32 pid;
  char name[TASK_COMM_LEN];
};

BPF_HASH(pid_cache, struct key_t, struct data_t);

BPF_PERF_OUTPUT(skb_events);

int process_frame(struct __sk_buff *skb) {
  // Data accessors
  unsigned char *data = (void *)(long)skb->data;
  unsigned char *data_end = (void *)(long)skb->data_end;

  // Mapping data to the Ethernet and IP headers
  struct ethhdr *eth = (struct ethhdr *)data;
  struct iphdr *iph = (struct iphdr*) (data + sizeof(struct ethhdr));

  // Simple length check
  if ((data + sizeof(struct ethhdr) + sizeof(struct iphdr)) > data_end)
    return TC_ACT_OK;

  // Discard everything but IPv4
  if (ntohs(eth->h_proto) != ETH_P_IP)
    return TC_ACT_OK;

  // Discard everything but TCP
  if (iph->protocol != IPPROTO_TCP)
    return TC_ACT_OK;

  // Retrieve the PID and the process name from the IP addresses
  struct key_t key = { .dst = iph->daddr, .src = iph->saddr };
  struct data_t *value = (struct data_t *) pid_cache.lookup(&key);
  if (value == NULL) {
    key.dst = iph->saddr;
    key.src = iph->daddr;
    value = (struct data_t *) pid_cache.lookup(&key);
    if (value == NULL)
      return TC_ACT_OK;
  }

  // Check the PID
  if (value->pid == 0)
    return TC_ACT_OK;

  struct data_t tmp;
  __builtin_memset(&tmp, 0, sizeof(tmp));     // it makes the eBPF verifier happy!
  tmp.pid = value->pid;
  for (u8 i=0; i < TASK_COMM_LEN; i++)
    tmp.name[i] = value->name[i];

  skb_events.perf_submit_skb(skb, skb->len, &tmp, sizeof(tmp));

  return TC_ACT_OK;
}

int kprobe_security_sk_classify_flow(struct pt_regs *ctx, struct sock *sk, struct flowi *fl) {
  // Discard everything but IPv4
  if (sk->sk_family != AF_INET)
    return 0;

  // Extract IPv4 related structures
  union flowi_uli uli;
  struct flowi4 ip4;
  bpf_probe_read(&ip4, sizeof(ip4), &fl->u.ip4);
  bpf_probe_read(&uli, sizeof(uli), &ip4.uli);

  // Get IP addresses and ports
  struct key_t key;
  struct data_t data;

  // it makes the eBPF verifier happy!
  __builtin_memset(&key, 0, sizeof(key));
  __builtin_memset(&data, 0, sizeof(data));

  bpf_probe_read(&key.src,
                 sizeof(sk->__sk_common.skc_daddr),
                 &sk->__sk_common.skc_daddr);
  bpf_probe_read(&key.dst,
                 sizeof(sk->__sk_common.skc_rcv_saddr),
                 &sk->__sk_common.skc_rcv_saddr);

  // Get and store the PID
  u64 id = bpf_get_current_pid_tgid();
  data.pid = id >> 32;

  // Get and store the process name
  bpf_get_current_comm(data.name, sizeof(data.name));

  // Store data
  pid_cache.update(&key, &data);

  return 0;
}


================================================
FILE: peetch/ebpf_programs/peetch_proxy.c
================================================
// SPDX-License-Identifier: GPL-2.0+
// Guillaume Valadon <gvaladon@quarkslab.com>

#include <linux/bpf.h>
#include <linux/in.h>

struct data_t {
  u32 pid;
  char name[64];
  u32 ip;
  u32 port;
};

BPF_HASH(pid_cache, u64);

BPF_HASH(destination_cache, u16, struct data_t);

int connect_v4_prog(struct bpf_sock_addr *ctx) {
  struct data_t data;

  // Get and store the PID
  u64 id = bpf_get_current_pid_tgid();
  data.pid = id >> 32;

  // Do not intercept connection from peetch itself
  if (PEETCH_PROXY_PID == data.pid)
    return 1;

  // Do not intercept well known TCP services
  if (ctx->user_port == bpf_htons(53)) // DNS
    return 1;

  // Check if the PID is in the cache
  u64 *tmp_id = pid_cache.lookup((u64*) &id);
  if (tmp_id == NULL)
    return 1;
  if (*tmp_id != id)
    return 1;

  // Get and store the process name
  bpf_get_current_comm(data.name, 64);

  // Rewrite the source port
  struct sockaddr_in sa = {};
	sa.sin_family = AF_INET;
  u16 new_port = bpf_htons(data.pid & 0xFFFF); // lower part of the PID will be used as the TCP source port
  sa.sin_port = new_port;
  sa.sin_addr.s_addr = bpf_htonl(0x7f000001); // 127.0.0.1

	if (bpf_bind(ctx, (struct sockaddr *) &sa, sizeof(sa)) != 0)
		return 0;

  // Get and store the real destination IPv4 address and port
  data.ip = ctx->user_ip4;
  data.port = ctx->user_port;

  // Store the connection data into the cache
  destination_cache.update(&new_port, &data);

  // Divert the connection to peetch proxy
  ctx->user_ip4 = 0x0100007f;
	ctx->user_port = bpf_htons(2807);

  /*
  Note:
  - 1: accept
  - 0: discard
  */
  return 1;
}

TRACEPOINT_PROBE(syscalls, sys_enter_openat) {
  #define _PATH_MAX 128
  char filename[_PATH_MAX + 1];

  // Retrieve the filename
  long ret = bpf_probe_read((void*)&filename, _PATH_MAX, (void*)args->filename);
   if (ret != 0) {
     //bpf_trace_printk("sys_enter_openat() - bpf_probe_read() failed\n");
     return 0;
   }

  // Check if the filename contains "libssl.so"
  for (u16 i=8; i < _PATH_MAX; i++) {
    if (filename[i-8] == 'l' && filename[i-7] == 'i'  && filename[i-6] == 'b' && filename[i-5] == 's' &&
        filename[i-4] == 's' && filename[i-3] == 'l'  && filename[i-2] == '.' && filename[i-1] == 's') {

      // Get and store the PID
      u64 id = bpf_get_current_pid_tgid();
      u64 pid = id >> 32;
      pid_cache.update(&id, &id);
      break;
    }
  }

  return 0;
}


================================================
FILE: peetch/ebpf_programs/peetch_uprobes.c
================================================
// SPDX-License-Identifier: GPL-2.0+
// Guillaume Valadon <gvaladon@quarkslab.com>

#include <linux/in.h>
#include <linux/ptrace.h>


// Data structure sent to userland
struct tls_event_t {
    u32 addr;
    u16 port;
    u16 tls_version;
    #define COMM_MAX_LEN 64
    char comm[COMM_MAX_LEN];
    #define MESSAGE_MAX_LEN 64
    u8 message[MESSAGE_MAX_LEN];
    u32 message_length;
    u32 pid;
    u32 is_read;
};
BPF_PERF_OUTPUT(tls_events);


// Store SSL_* buffer information
struct SSL_buffer_t {
    u64 ptr;
    u32 length;
    u32 tls_version;
    u32 is_read;
};
BPF_HASH(SSL_read_buffers, u32, struct SSL_buffer_t);


// Store connect information indexed by PID
BPF_HASH(pid_cache, u32);


// TLS information
struct TLS_information_t {
    u16 tls_version;
    #define CIPHERSUITE_MAX_LEN 32
    char ciphersuite[CIPHERSUITE_MAX_LEN];
    #define MASTER_SECRET_MAX_LEN 48
    u8 master_secret[MASTER_SECRET_MAX_LEN];
    #define CLIENT_RANDOM_MAX_LEN 32
    u8 client_random[CLIENT_RANDOM_MAX_LEN];
};
BPF_HASH(tls_information_cache, u32, struct TLS_information_t);


TRACEPOINT_PROBE(syscalls, sys_enter_connect) {
    // Retrieve the sockaddr_in structure
    struct sockaddr_in addr_in;
    long ret = bpf_probe_read((void*)&addr_in, sizeof(addr_in), args->uservaddr);
    if (ret != 0) {
        bpf_trace_printk("sys_enter_connect() - bpf_probe_read() failed\n");
        return 0;
    }

    // Discard everything but IPv4
    if (addr_in.sin_family != AF_INET)
        return 0;

    // Retrieve the PID
    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;

    // Store a TLS event in the pid_cache
    struct tls_event_t event = { .port = addr_in.sin_port,
                                 .addr = addr_in.sin_addr.s_addr};
    pid_cache.update(&pid, (u64*)&event);

    return 0;
}


// Dummy openssl ssl_st structure
struct ssl_st {
    int version;
};


static u16 get_tls_version(void *ssl_st_ptr) {
    // Extract the TLS version from a struct ssl_str pointer
    struct ssl_st ssl;

    long ret = bpf_probe_read(&ssl, sizeof(ssl), ssl_st_ptr);
    if (ret != 0) {
        bpf_trace_printk("get_tls_version() - bpf_probe_read() failed\n");
        return -1;
    }

    return ssl.version;
}


static void parse_session(struct pt_regs *ctx, u16 tls_version) {
    // Parse a struct sl_session_st pointer and send
    // data to userspace

    // TLS information sent to userspace
    struct TLS_information_t tls_information;
    __builtin_memset(&tls_information, 0, sizeof(tls_information)); // it makes the eBPF verifier happy!
    tls_information.tls_version = tls_version;

    // Get a ssl_st pointer
    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);

    // Get a ssl_session_st pointer
    u64 *ssl_session_st_ptr = (u64 *) (ssl_st_ptr + SSL_SESSION_OFFSET);

    u64 address;
    long ret = bpf_probe_read(&address, sizeof(address), ssl_session_st_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #1 - bpf_probe_read() failed\n");

    // Access the TLS 1.2 master secret
    void *ms_ptr = (void *) (address + MASTER_SECRET_OFFSET);
    ret = bpf_probe_read(&tls_information.master_secret,
                              sizeof(tls_information.master_secret), ms_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #2 - bpf_probe_read() failed\n");

    // Get a ssl_cipher_st pointer
    void *ssl_cipher_st_ptr = (void *) (address + SSL_CIPHER_OFFSET);
    ret = bpf_probe_read(&address, sizeof(address), ssl_cipher_st_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #3 - bpf_probe_read() failed\n");

    // Get the SSL_cipher_st point to the name member
    ssl_cipher_st_ptr = (void *) (address + 8);
    ret = bpf_probe_read(&address, sizeof(address), ssl_cipher_st_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #4 - bpf_probe_read() failed\n");

    // Access the TLS ciphersuite
    void *cs_ptr = (void *) address;
    ret = bpf_probe_read(&tls_information.ciphersuite,
                              sizeof(tls_information.ciphersuite), cs_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #5 - bpf_probe_read() failed\n");

    // Retrieve the Client Random
    void* client_hello_ptr = (void *) (ssl_st_ptr + CLIENT_HELLO_OFFSET);
    ret = bpf_probe_read(&address, sizeof(address), client_hello_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #6 - bpf_probe_read() failed\n");

    u8 client_random[CLIENT_RANDOM_MAX_LEN + CLIENT_RANDOM_OFFSET];
    ret = bpf_probe_read(client_random, sizeof(client_random), client_hello_ptr);
    if (ret != 0)
        bpf_trace_printk("parse_session() #7 - bpf_probe_read() failed\n");

    ret = bpf_probe_read(&tls_information.client_random, sizeof(tls_information.client_random), client_random + CLIENT_RANDOM_OFFSET);
    if (ret != 0)
        bpf_trace_printk("parse_session() #8 - bpf_probe_read() failed\n");

    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;
    tls_information_cache.update(&pid, &tls_information);
}


static int SSL_read_write(struct pt_regs *ctx, u16 tls_version, struct SSL_buffer_t *buffer) {
    // A buffer is needed
    if (buffer == NULL)
        return 0;

    // Retrieve connect() information for PID
    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;
    struct tls_event_t *event = (struct tls_event_t*) pid_cache.lookup(&pid);
    if (event == NULL) {
    
    	//get ppid to check if it is a child of a known process 
    	struct task_struct *task;
		task = (struct task_struct *)bpf_get_current_task();
		pid = task->real_parent->tgid;
		
		event = (struct tls_event_t*) pid_cache.lookup(&pid);
    	if(event == NULL)
    		return 0;
    }

    // Build a new TLS event and fill it
    struct tls_event_t new_event;

    bpf_get_current_comm(&new_event.comm, COMM_MAX_LEN);
    new_event.pid = pid;
    new_event.port = event->port;
    new_event.addr = event->addr;
    new_event.is_read = buffer->is_read;
    new_event.tls_version = tls_version;

    long ret = bpf_probe_read(&new_event.message,
                             sizeof(new_event.message), (void*) buffer->ptr);
    if (ret != 0) {
        bpf_trace_printk("SSL_read_write() - bpf_probe_read() failed\n");
        return 0;
    }
    new_event.message_length = buffer->length;

    // Send the event to userland
    tls_events.perf_submit(ctx, &new_event, sizeof(new_event));

    // Flush the PID cache
    if (DIRECTIONS)  // this will be replaced by a boolean in Python
        pid_cache.delete(&pid);

    return 0;
}


int SSL_read(struct pt_regs *ctx) {
    // Retrieve the PID
    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;

    // Store a SSL read buffer information in the cache
    struct SSL_buffer_t buffer;
    __builtin_memset(&buffer, 0, sizeof(buffer));
    buffer.ptr = PT_REGS_PARM2(ctx);

    // Get TLS version
    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);
    buffer.tls_version = get_tls_version(ssl_st_ptr);

    SSL_read_buffers.update(&pid, &buffer);

    return 0;
}


int SSL_read_ret(struct pt_regs *ctx) {
    // Discard if nothing was received
    int buffer_length = PT_REGS_RC(ctx);
    if (buffer_length == -1)
        return 0;

    // Retrieve SSL read buffers information for PID
    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;
    struct SSL_buffer_t *buffer = (struct SSL_buffer_t*) SSL_read_buffers.lookup(&pid);
    if (buffer == NULL)
        return 0;

    // Add buffer information
    buffer->length = buffer_length;
    buffer->is_read = 1;

    long ret = SSL_read_write(ctx, buffer->tls_version, buffer);
    SSL_read_buffers.delete(&pid);

    return ret;
}


int SSL_write(struct pt_regs *ctx) {
    // Retrieve the buffer information
    struct SSL_buffer_t buffer;

    buffer.ptr = PT_REGS_PARM2(ctx);
    buffer.length = PT_REGS_PARM3(ctx);
    buffer.is_read = 0;

    // Get TLS version
    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);
    u16 tls_version = get_tls_version(ssl_st_ptr);

    parse_session(ctx, tls_version);

    return SSL_read_write(ctx, tls_version, &buffer);
}


================================================
FILE: peetch/globals.py
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

BPF_HANDLER = None
BPF_TLS_HANDLER = None
PACKETS_CAPTURED = []
TLS_INFORMATION = {}


================================================
FILE: peetch/proxy.py
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

import asyncio
import binascii
import ctypes as ct
import socket
import struct
import sys
import time

from scapy.all import sniff, IP, TCP, conf

import peetch.globals


def retrieve_client_information(bpf_handler, port_src):
    """
    Get client information from eBPF maps
    """

    process_name, process_pid, ip_dst, port_dst = [None] * 4
    bpf_map_destination_cache = bpf_handler["destination_cache"]

    destination_key_to_delete = None

    for destination_key, destination_data in bpf_map_destination_cache.items_lookup_batch():  # noqa: E501
        process_pid = destination_data.pid
        process_name = destination_data.name.decode("ascii", "replace")

        # Retrieve destination IP and port
        address_packed = struct.pack("I", destination_data.ip)
        ip_dst = socket.inet_ntop(socket.AF_INET, address_packed)
        port_dst = socket.ntohs(destination_data.port)

        if socket.ntohs(destination_key.value) == port_src:
            ct_array = ct.c_uint16 * 1
            destination_key_to_delete = ct_array(destination_key)
            break

    if destination_key_to_delete:
        bpf_map_destination_cache.items_delete_batch(destination_key_to_delete)

    return process_name, process_pid, ip_dst, port_dst


def retrieve_tls_information(bpf_handler, process_pid):
    """
    Get TLS information from eBPF maps
    """
    tls_version, ciphersuite, client_random, master_secret = [None] * 4

    retries = 5
    pid_to_delete = None
    bpf_map_tls_information = bpf_handler["tls_information_cache"]
    while pid_to_delete is None and retries:
        retries -= 1
        for pid, tls_info in bpf_map_tls_information.items_lookup_batch():
            if pid.value == process_pid:
                ciphersuite = tls_info.ciphersuite.decode("ascii", "ignore")
                master_secret = binascii.hexlify(tls_info.master_secret)
                master_secret = master_secret.decode("ascii", "ignore")
                client_random = binascii.hexlify(tls_info.client_random)
                client_random = client_random.decode("ascii", "ignore")
                tls_version = (tls_info.tls_version & 0xF) - 1
                if len(ciphersuite):
                    ct_array = ct.c_uint * 1
                    pid_to_delete = ct_array(pid)
                    break
        #time.sleep(0.005)

    # Delete pid from the eBPF map
    if pid_to_delete:
        bpf_map_tls_information.items_delete_batch(pid_to_delete)

    return tls_version, ciphersuite, client_random, master_secret


async def dots():
    """
    print dots
    """
    while True:
        await asyncio.sleep(0.5)
        print(".", end="", flush=True)


def decrypt_messages(tls_information, packets):
    """
    Decrypt and display messages
    """

    tls_version = tls_information.get("version", sys.maxsize)
    if tls_version < 3:
        for p in sniff(offline=packets):
            if TLSApplicationData in p:  # noqa: F821
                print()
                p[TLSApplicationData].show()  # noqa: F821


async def handle_client(local_reader, local_writer):
    """
    Proxy a new client connection
    """

    # Retrieve source IP and port used to connect to the proxy
    ip_src, port_src = local_reader._transport.get_extra_info("peername")

    # Retrieve process information, and destination IP and port
    tmp = retrieve_client_information(peetch.globals.BPF_HANDLER, port_src)
    process_name, process_pid, ip_dst, port_dst = tmp

    if process_name is None:
        print("[!] Did not find the real destination")
        local_writer.close()
        return

    print("", flush=True)
    print(f"\r[+] Intercepting traffic from {process_name}/{process_pid}", end="")  # noqa: E501
    print(f" to {ip_dst}/{port_dst} via {ip_src}/{port_src}")

    try:
        # Connect to the real destination and copy data between sockets
        tmp = await asyncio.open_connection(ip_dst, port_dst)
        remote_reader, remote_writer = tmp
        pipe1 = pipe(local_reader, remote_writer, process_pid,
                     "-->", ip_src, ip_dst, port_src, port_dst)
        pipe2 = pipe(remote_reader, local_writer, process_pid,
                     "<--", ip_dst, ip_src, port_dst, port_src)
        await asyncio.gather(pipe1, pipe2)

        # Decrypt and display TLS messages
        decrypt_messages(peetch.globals.TLS_INFORMATION,
                         peetch.globals.PACKETS_CAPTURED)

        # Reset global variables
        conf.tls_nss_keys = {}
        peetch.globals.TLS_INFORMATION = {}
        peetch.globals.PACKETS_CAPTURED = []
    except ConnectionResetError as e:
        print(f"   {e}")
    finally:
        local_writer.close()


async def pipe(reader, writer, pid, direction, ip_src, ip_dst, port_src, port_dst):  # noqa: E501
    """"
    Copy data from one socket to another and retrieve TLS information
    Inspired by https://stackoverflow.com/a/46422554
    """

    try:
        while not reader.at_eof():
            data = await reader.read(8192)
            if not len(data):
                continue

            # Rebuild the IP packet
            tls_record = IP(dst=ip_dst, src=ip_src)
            tls_record /= TCP(dport=port_dst, sport=port_src)
            tls_record /= TLS(data)  # noqa: F821
            peetch.globals.PACKETS_CAPTURED += [tls_record]

            # Display a short summary
            sprintf_fmt = "%IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport% %IP.proto%"  # noqa: E501
            summary = tls_record.sprintf(sprintf_fmt)
            print(f"    {direction} {summary}")

            # Copy data to the other socket
            writer.write(data)

            # Get and store TLS information
            tls_version, ciphersuite, client_random, master_secret = retrieve_tls_information(peetch.globals.BPF_TLS_HANDLER, pid)  # noqa: E501
            if ciphersuite:
                if tls_version < 3:
                    client_random_bytes = binascii.unhexlify(client_random)
                    master_secret_bytes = binascii.unhexlify(master_secret)
                    conf.tls_nss_keys = {"CLIENT_RANDOM": {client_random_bytes: master_secret_bytes}}  # noqa: E501
                    peetch.globals.TLS_INFORMATION = {"version": tls_version,
                                                      "ciphersuite": ciphersuite}  # noqa: E501
    finally:
        writer.close()


async def tcp_proxy():
    """
    async TCP proxy
    """
    server = await asyncio.start_server(handle_client, "127.0.0.1", 2807)
    await server.serve_forever()


async def all_tasks(debug):
    """
    all proxy tasks
    """
    tasks = [tcp_proxy()]
    if debug:
        tasks += [dots()]
    await asyncio.gather(*tasks)


================================================
FILE: peetch/utils.py
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

import ctypes
import os
import os.path
import sys

# Identify the library path
dirname = os.path.dirname(__file__)
UTILS_LIB_PATH = None
for root, dirs, files in os.walk(dirname):
    for file in files:
        if file.startswith("utils_lib") and file.endswith(".so"):
            UTILS_LIB_PATH = os.path.join(root, file)
            break


class LIBSSLOffsets(ctypes.Structure):
    _fields_ = [("ssl_session", ctypes.c_uint64),
                ("ssl_cipher", ctypes.c_uint64),
                ("master_secret", ctypes.c_uint64),
                ("client_hello", ctypes.c_uint64),
                ("client_random", ctypes.c_uint64)]


if UTILS_LIB_PATH:
    libssl_offset = ctypes.CDLL(UTILS_LIB_PATH)
    libssl_offset.libssl_offsets.argstypes = [ctypes.c_char_p, ctypes.c_uint16]
    libssl_offset.libssl_offsets.restype = LIBSSLOffsets

    def get_offsets(address_ipv4=b"1.1.1.1", port=443):
        # Retrieve offsets inside SSL structures
        raw_offsets = libssl_offset.libssl_offsets(address_ipv4, port)
        return (raw_offsets.ssl_session,
                raw_offsets.ssl_cipher,
                raw_offsets.master_secret,
                raw_offsets.client_hello,
                raw_offsets.client_random)
else:
    print("ERROR: cannot find the utils_lib dynamic library!", file=sys.stderr)
    sys.exit(1)

if __name__ == "__main__":
    print(["0x%x" % offset for offset in get_offsets()])


================================================
FILE: requirements.txt
================================================
scapy @ git+https://github.com/secdev/scapy@master
cryptography
pyroute2


================================================
FILE: setup.py
================================================
# SPDX-License-Identifier: GPL-2.0+
# Guillaume Valadon <gvaladon@quarkslab.com>

from distutils.core import setup, Extension

setup(name="peetch",
      description="An eBPF playground",
      author="Guillaume Valadon",
      author_email="gvaladon@quarkslab.com",
      version="0.2.0",
      packages=["peetch"],
      package_data={"peetch": ["ebpf_programs/peetch_*.c"]},
      entry_points={"console_scripts": ["peetch=peetch:main"]},
      ext_modules=[Extension("peetch.utils_lib", sources=["peetch/c_utils/libssl.c"], libraries=["ssl"])],
      )
Download .txt
gitextract_b_gn6amn/

├── Dockerfile
├── LICENSE.txt
├── README.md
├── doc/
│   └── notes.md
├── peetch/
│   ├── __init__.py
│   ├── __main__.py
│   ├── c_utils/
│   │   └── libssl.c
│   ├── ebpf_programs/
│   │   ├── peetch_kprobes.c
│   │   ├── peetch_proxy.c
│   │   └── peetch_uprobes.c
│   ├── globals.py
│   ├── proxy.py
│   └── utils.py
├── requirements.txt
└── setup.py
Download .txt
SYMBOL INDEX (42 symbols across 7 files)

FILE: peetch/__init__.py
  function load_classifier (line 41) | def load_classifier(interface, ebpf_function):
  function unload_classifier (line 65) | def unload_classifier(interface):
  function exit_handler_command (line 72) | def exit_handler_command(interface, filename, bpf_handler):
  function exit_handler_proxy (line 84) | def exit_handler_proxy(bpf_handler, connect_function, cgroup_fd):
  function handle_skb_event (line 95) | def handle_skb_event(cpu, data, size):
  function dump_command (line 130) | def dump_command(args):
  function handle_tls_event (line 155) | def handle_tls_event(cpu, data, size):
  function _tls_ebpf_programs (line 226) | def _tls_ebpf_programs(directions_bool, args_ssl_session_offset,
  function tls_command (line 270) | def tls_command(args):
  function proxy_command (line 386) | def proxy_command(args):
  function main (line 435) | def main():

FILE: peetch/c_utils/libssl.c
  type libssl_offsets_t (line 12) | struct libssl_offsets_t {
  function libssl_offsets (line 21) | struct libssl_offsets_t libssl_offsets(char *ip4_address, uint16_t port) {
  function main (line 146) | int main() {

FILE: peetch/ebpf_programs/peetch_kprobes.c
  type key_t (line 15) | struct key_t {
  type data_t (line 20) | struct data_t {
  function process_frame (line 29) | int process_frame(struct __sk_buff *skb) {
  function kprobe_security_sk_classify_flow (line 76) | int kprobe_security_sk_classify_flow(struct pt_regs *ctx, struct sock *s...

FILE: peetch/ebpf_programs/peetch_proxy.c
  type data_t (line 7) | struct data_t {
  function connect_v4_prog (line 18) | int connect_v4_prog(struct bpf_sock_addr *ctx) {

FILE: peetch/ebpf_programs/peetch_uprobes.c
  type tls_event_t (line 9) | struct tls_event_t {
  type SSL_buffer_t (line 25) | struct SSL_buffer_t {
  type TLS_information_t (line 39) | struct TLS_information_t {
  type sockaddr_in (line 53) | struct sockaddr_in
  type tls_event_t (line 68) | struct tls_event_t
  type ssl_st (line 77) | struct ssl_st {
  function u16 (line 82) | static u16 get_tls_version(void *ssl_st_ptr) {
  function parse_session (line 96) | static void parse_session(struct pt_regs *ctx, u16 tls_version) {
  function SSL_read_write (line 162) | static int SSL_read_write(struct pt_regs *ctx, u16 tls_version, struct S...
  function SSL_read (line 211) | int SSL_read(struct pt_regs *ctx) {
  function SSL_read_ret (line 230) | int SSL_read_ret(struct pt_regs *ctx) {
  function SSL_write (line 253) | int SSL_write(struct pt_regs *ctx) {

FILE: peetch/proxy.py
  function retrieve_client_information (line 17) | def retrieve_client_information(bpf_handler, port_src):
  function retrieve_tls_information (line 47) | def retrieve_tls_information(bpf_handler, process_pid):
  function dots (line 79) | async def dots():
  function decrypt_messages (line 88) | def decrypt_messages(tls_information, packets):
  function handle_client (line 101) | async def handle_client(local_reader, local_writer):
  function pipe (line 146) | async def pipe(reader, writer, pid, direction, ip_src, ip_dst, port_src,...
  function tcp_proxy (line 185) | async def tcp_proxy():
  function all_tasks (line 193) | async def all_tasks(debug):

FILE: peetch/utils.py
  class LIBSSLOffsets (line 19) | class LIBSSLOffsets(ctypes.Structure):
  function get_offsets (line 32) | def get_offsets(address_ipv4=b"1.1.1.1", port=443):
Condensed preview — 15 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (75K chars).
[
  {
    "path": "Dockerfile",
    "chars": 1021,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nFROM ubuntu:22.04\n\nENV TZ=Europe/Paris"
  },
  {
    "path": "LICENSE.txt",
    "chars": 18092,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Fr"
  },
  {
    "path": "README.md",
    "chars": 5798,
    "preview": "# peetch\n\n`peetch` is a collection of tools aimed at experimenting with different aspects of eBPF to bypass TLS protocol"
  },
  {
    "path": "doc/notes.md",
    "chars": 1796,
    "preview": "# Notes\n\nThis document contains various information used to debug and test `peetch` features.\n\n# Tests\n\n* `openssl s_cli"
  },
  {
    "path": "peetch/__init__.py",
    "chars": 18221,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport argparse\nimport asyncio\nimport "
  },
  {
    "path": "peetch/__main__.py",
    "chars": 132,
    "preview": "#!/usr/bin/env python3\n# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nfrom . import m"
  },
  {
    "path": "peetch/c_utils/libssl.c",
    "chars": 4353,
    "preview": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <arpa/inet.h>\n#include <net"
  },
  {
    "path": "peetch/ebpf_programs/peetch_kprobes.c",
    "chars": 2880,
    "preview": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/if_ether.h>\n#include"
  },
  {
    "path": "peetch/ebpf_programs/peetch_proxy.c",
    "chars": 2415,
    "preview": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/bpf.h>\n#include <lin"
  },
  {
    "path": "peetch/ebpf_programs/peetch_uprobes.c",
    "chars": 8070,
    "preview": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/in.h>\n#include <linu"
  },
  {
    "path": "peetch/globals.py",
    "chars": 167,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nBPF_HANDLER = None\nBPF_TLS_HANDLER = N"
  },
  {
    "path": "peetch/proxy.py",
    "chars": 6801,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport asyncio\nimport binascii\nimport "
  },
  {
    "path": "peetch/utils.py",
    "chars": 1497,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport ctypes\nimport os\nimport os.path"
  },
  {
    "path": "requirements.txt",
    "chars": 73,
    "preview": "scapy @ git+https://github.com/secdev/scapy@master\ncryptography\npyroute2\n"
  },
  {
    "path": "setup.py",
    "chars": 557,
    "preview": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nfrom distutils.core import setup, Exte"
  }
]

About this extraction

This page contains the full source code of the quarkslab/peetch GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 15 files (70.2 KB), approximately 18.7k tokens, and a symbol index with 42 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!