[
  {
    "path": "Dockerfile",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nFROM ubuntu:22.04\n\nENV TZ=Europe/Paris DEBIAN_FRONTEND=noninteractive\nRUN echo 'PS1=\"quarkslab/peetch:\\w# \"' >> /root/.bashrc\n\n# Install dependencies\nRUN set -x && \\\n    PACKAGES=\"bison build-essential cmake flex git \\\n    libedit-dev libllvm11 llvm-11-dev libclang-11-dev python3 zlib1g-dev \\\n    libelf-dev libfl-dev python3-distutils python3-pip linux-headers-$(uname -r) \\\n    libssl-dev iproute2 tmux curl bc libelf-dev zip tshark curl\" && \\\n    apt-get update && apt-get install -y $PACKAGES && \\\n    apt-get autoclean && apt-get --purge -y autoremove && \\\n    rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*\n\n# Compile bcc\nRUN git clone https://github.com/iovisor/bcc && cd bcc/ && mkdir build && \\\n    cd build && cmake .. && make install && cd src && make install && rm -rf /bcc/\n\n# Install peetch\nCOPY . /peetch\nRUN cd /peetch && pip install --upgrade pip && pip install -r requirements.txt && \\\n    pip install . && rm -rf /peetch"
  },
  {
    "path": "LICENSE.txt",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "# peetch\n\n`peetch` is a collection of tools aimed at experimenting with different aspects of eBPF to bypass TLS protocol protections.\n\nCurrently, 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.\n\nCombined, the first two commands make it possible to decrypt TLS exchanges recorded in the PCAPng format.\n\n## Installation\n\n`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:\n\n```shell\ndocker build -t quarkslab/peetch .\n```\n\n## Commands Walk Through\n\nThe following examples assume that you used the following command to enter the Docker image and launch examples within it:\n\n```shell\ndocker run --privileged --network host --mount type=bind,source=/sys,target=/sys --mount type=bind,source=/proc,target=/proc --pid host --rm -it quarkslab/peetch\n```\n\n### `dump`\n\nThis sub-command gives you the ability to sniff packets using an eBPF TC classifier and to retrieve the corresponding PID and process names with:\n\n```shell\npeetch dump\ncurl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https S / Padding\ncurl/1289291 - Ether / IP / TCP 208.97.177.124:https > 10.211.55.10:53052 SA / Padding\ncurl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https A / Padding\ncurl/1289291 - Ether / IP / TCP 10.211.55.10:53052 > 208.97.177.124:https PA / Raw / Padding\ncurl/1289291 - Ether / IP / TCP 208.97.177.124:https > 10.211.55.10:53052 A / Padding\n```\n\nNote that as of today, `dump` will only capture IPv4 based TCP segments.\n\nFor convenience, the captured packets can be store to PCAPng along with process information using `--write`:\n\n```shell\npeetch dump --write peetch.pcapng\n^C\n```\n\nThis PCAPng can easily be manipulated with Wireshark or Scapy:\n\n```python\nscapy\n>>> l = rdpcap(\"peetch.pcapng\")\n>>> l[0]\n<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' |>>>>\n>>> l[0].comment\nb'curl/1289909'\n```\n\n### `tls`\n\nThis sub-command aims to identify processes that uses OpenSSL and makes it easy to dump several things like plaintext and secrets.\n\nBy default, `peetch tls` will only display one line per process, the `--directions` argument makes it possible to display the exchanged messages:\n\n```shell\npeetch tls --directions\n<- curl (1291078) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256\n-> curl (1291078) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256\n```\n\nDisplaying OpenSSL buffer content is achieved with `--content`.\n\n```shell\npeetch tls --content\n<- curl (1290608) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256\n\n   0000  47 45 54 20 2F 20 48 54 54 50 2F 31 2E 31 0D 0A  GET / HTTP/1.1..\n   0010  48 6F 73 74 3A 20 77 77 77 2E 70 65 72 64 75 2E  Host: www.perdu.\n   0020  63 6F 6D 0D 0A 55 73 65 72 2D 41 67 65 6E 74 3A  com..User-Agent:\n   0030  20 63 75 72 6C 2F 37 2E 36 38 2E 30 0D 0A 41 63   curl/7.68.0..Ac\n\n-> curl (1290608) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256\n\n   0000  48 54 54 50 2F 31 2E 31 20 32 30 30 20 4F 4B 0D  HTTP/1.1 200 OK.\n   0010  0A 44 61 74 65 3A 20 54 68 75 2C 20 31 39 20 4D  .Date: Thu, 19 M\n   0020  61 79 20 32 30 32 32 20 31 38 3A 31 36 3A 30 31  ay 2022 18:16:01\n   0030  20 47 4D 54 0D 0A 53 65 72 76 65 72 3A 20 41 70   GMT..Server: Ap\n```\n\nThe `--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:\n\n```shell\n(sleep 5; curl https://www.perdu.com/?name=highly%20secret%20information --tls-max 1.2 --http1.1 --tlsv1.2) &\n\npeetch tls --write &\ncurl (1293232) 208.97.177.124/443 TLS1.2 ECDHE-RSA-AES128-GCM-SHA256\n\npeetch dump --write traffic.pcapng\n^C\n\n# Add the master secret to a PCAPng file\neditcap --inject-secrets tls,1293232-master_secret.log traffic.pcapng traffic-ms.pcapng\n\nscapy\n>>> load_layer(\"tls\")\n>>> conf.tls_session_enable = True\n>>> l = rdpcap(\"traffic-ms.pcapng\")\n>>> l[13][TLS].msg\n[<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' |>]\n```\n\n### `proxy`\n\nThis sub-command uses eBPF programs to automatically intercept TLS traffic from processes using OpenSSL and decrypt messages on the fly using Scapy.\n\nIn the following example, `peetch proxy` display a secret value sent to a server by the `openssl` process.\n\n```shell\npeetch proxy\n[-] Proxying OpenSSL traffic\n[+] Intercepting traffic from openssl/451255 to 172.67.133.176/443 via 127.0.0.1/58039\n    --> 127.0.0.1:58039 > 172.67.133.176:https tcp\n    <-- 172.67.133.176:https > 127.0.0.1:58039 tcp\n    --> 127.0.0.1:58039 > 172.67.133.176:https tcp\n    <-- 172.67.133.176:https > 127.0.0.1:58039 tcp\n    --> 127.0.0.1:58039 > 172.67.133.176:https tcp\n    --> 127.0.0.1:58039 > 172.67.133.176:https tcp\n\n###[ TLS Application Data ]###\n  data      = b'GET /?secret=9590 HTTP/1.1\\r\\nHost: www.perdu.com\\r\\n\\r\\n\\n'\n```\n\n## Limitations\n\nBy design, `peetch` only supports OpenSSL, IPv4 and TLS 1.2.\n"
  },
  {
    "path": "doc/notes.md",
    "content": "# Notes\n\nThis document contains various information used to debug and test `peetch` features.\n\n# Tests\n\n* `openssl s_client`\n```\nrm 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\n```\n\n* test the connectin to the proxy\n```\ncurl --connect-to www.perdu.com:443:127.0.0.1:2807 https://www.perdu.com\n```\n\n* libcurl binaries\n```\n# TLS1.2 & HTTP/1.1\ncurl https://echo.free.beeceptor.com/?secret_number=$RANDOM --tls-max 1.2 --http1.1 --tlsv1.2 --libcurl secret_binary.c\ncc -o secret_binary secret_binary.c -lssl -lcurl && ./secret_binary\n\n# TLS1.2 & HTTP/2.0\ncurl https://echo.free.beeceptor.com/?secret_number=$RANDOM --tls-max 1.2 --http2 --tlsv1.2 --libcurl secret_binary2.c\ncc -o secret_binary2 secret_binary2.c -lssl -lcurl && ./secret_binary2\n```\n\n# OpenSSL Offsets\n\nThe following radare2 commands could be used to validate the OpenSSL offsets dynamically generated by `peetch`:\n\n```\ncat curl.rr2\n#!/usr/bin/rarun2\nprogram=/usr/bin/curl\narg0=5\narg1=--tls-max\narg2=1.2\narg3=--tlsv1.2\narg4=--http1.1\narg5=https://www.perdu.com\n\nradare2 -e dbg.profile=curl.rr2 -A -d /usr/bin/curl\n[...]> dcu sym.imp.curl_globa_init\n[...]> dmi libssl SSL_read\n[...]> dmi libssl SSL_write\n[...]> db 0xffffa479eeb4 # address of SSL_read\n[...]> db 0xffff9086f504 # address of SSL_write\n[...]> dc\n\n[...]> px 48 @ `pv @ x0 + 0x918` + 0x50 # offset off ssl_session and master_secret\n- offset - 6061 6263 6465 6667 6869 6A6B 6C6D 6E6F 0123456789ABCDEF\n0xaaab0a47aa60 ce6a 7675 5e95 dfd4 e5ed 10c1 c0b7 9bd9 .jvu^...........\n0xaaab0a47aa70 808f 416a 13ef cb29 6c8e 323a 40cb e5ea ..Aj...)l.2:@...\n0xaaab0a47aa80 ccdb 09d2 7f46 7fb9 7115 6082 f4dc 2725 .....F..q.`...'%\n```\n```"
  },
  {
    "path": "peetch/__init__.py",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport argparse\nimport asyncio\nimport atexit\nimport ctypes as ct\nimport binascii\nimport os\nimport socket\nimport struct\nimport sys\nimport time\n\nfrom bcc import BPF, BPFProgType, BPFAttachType\nimport pyroute2\nfrom scapy.all import Ether, wrpcapng, hexdump, load_layer, conf\n\nimport peetch.globals\nfrom peetch.proxy import all_tasks\nimport peetch.utils\n\n\nload_layer(\"tls\")\nconf.tls_session_enable = True\n\nglobal BPF_HANDLER, BPF_TLS_HANDLER\n\nEBPF_PROGRAMS_DIRNAME = os.path.join(os.path.dirname(__file__),\n                                     \"ebpf_programs/\")\nBPF_DUMP_PROGRAM_FILENAME = \"%s/peetch_kprobes.c\" % EBPF_PROGRAMS_DIRNAME\nBPF_DUMP_PROGRAM_SOURCE = open(BPF_DUMP_PROGRAM_FILENAME).read()\nBPF_TLS_PROGRAM_FILENAME = \"%s/peetch_uprobes.c\" % EBPF_PROGRAMS_DIRNAME\nBPF_TLS_PROGRAM_SOURCE = open(BPF_TLS_PROGRAM_FILENAME).read()\nBPF_PROXY_PROGRAM_FILENAME = \"%s/peetch_proxy.c\" % EBPF_PROGRAMS_DIRNAME\nBPF_PROXY_PROGRAM_SOURCE = open(BPF_PROXY_PROGRAM_FILENAME).read()\nPACKETS_CAPTURED = []\nTLS_INFORMATION = {}\n\n\ndef load_classifier(interface, ebpf_function):\n    \"\"\"\n    Load an eBPF TC Classifier\n    \"\"\"\n    iproute_handler = pyroute2.IPRoute()\n\n    ip_link = iproute_handler.link_lookup(ifname=interface)\n    if not ip_link:\n        sys.exit()\n\n    ip_link = ip_link[0]\n    iproute_handler.tc(\"add\", \"clsact\", ip_link)\n\n    # add ingress clsact\n    iproute_handler.tc(\"add-filter\", \"bpf\", ip_link, \":1\",\n                       fd=ebpf_function.fd, name=ebpf_function.name,\n                       parent=\"ffff:fff2\")\n\n    # add egress clsact\n    iproute_handler.tc(\"add-filter\", \"bpf\", ip_link, \":1\",\n                       fd=ebpf_function.fd, name=ebpf_function.name,\n                       parent=\"ffff:fff3\")\n\n\ndef unload_classifier(interface):\n    \"\"\"\n    Unload an eBPF TC Classifier\n    \"\"\"\n    os.system(\"tc qdisc del dev %s clsact\" % args.interface)\n\n\ndef exit_handler_command(interface, filename, bpf_handler):\n    \"\"\"\n    Exit command nicely\n    \"\"\"\n    time.sleep(0.01)\n    bpf_handler.detach_kprobe(event=\"security_sk_classify_flow\",\n                              fn_name=\"kprobe_security_sk_classify_flow\")\n    unload_classifier(interface)\n    if filename:\n        wrpcapng(filename, PACKETS_CAPTURED)\n\n\ndef exit_handler_proxy(bpf_handler, connect_function, cgroup_fd):\n    \"\"\"\n    Exit proxy nicely\n    \"\"\"\n    time.sleep(0.01)\n    bpf_handler.detach_func(connect_function, cgroup_fd,\n                            BPFAttachType.CGROUP_INET4_CONNECT)\n    if cgroup_fd > 0:\n        os.close(cgroup_fd)\n\n\ndef handle_skb_event(cpu, data, size):\n    \"\"\"\n    Handle SKB events from the kernel\n    \"\"\"\n\n    # Structure retrieved from the kernel\n    class SkbEvent(ct.Structure):\n        _fields_ = [(\"pid\", ct.c_uint32),\n                    (\"raw\", ct.c_ubyte * (size - ct.sizeof(ct.c_uint32)))]\n\n    # Map the data from kernel to the structure\n    skb_event = ct.cast(data, ct.POINTER(SkbEvent)).contents\n    data = bytes(skb_event.raw)\n\n    # Extract the process name\n    for i in range(len(data)):\n        if data[i] == 0:\n            break\n    process_name = data[:i].decode(\"utf-8\", \"replace\")\n    data = data[16:]\n\n    process_information = \"%s/%d\" % (process_name, skb_event.pid)\n\n    # Parse the packet with Scapy\n    pkt = Ether(data)\n\n    if args.write:\n        pkt.comment = str(process_information)\n        PACKETS_CAPTURED.append(pkt)\n    else:\n        if not args.raw:\n            print(process_information, end=\" - \")\n        print(pkt.summary())\n\n\ndef dump_command(args):\n    # Compile eBPF programs\n    bpf_handler = BPF(text=BPF_DUMP_PROGRAM_SOURCE)\n\n    # Attach the kprobe\n    bpf_handler.attach_kprobe(event=\"security_sk_classify_flow\",\n                              fn_name=\"kprobe_security_sk_classify_flow\")\n\n    # Setup the exit handler\n    atexit.register(exit_handler_command, args.interface, args.write,\n                    bpf_handler)\n\n    # Load eBPF TC Classifier\n    classifier_function = bpf_handler.load_func(\"process_frame\", BPF.SCHED_CLS)\n    load_classifier(args.interface, classifier_function)\n\n    # Handle incoming skb events\n    bpf_handler[\"skb_events\"].open_perf_buffer(handle_skb_event)\n    try:\n        while True:\n            bpf_handler.perf_buffer_poll()\n    except KeyboardInterrupt:\n        pass\n\n\ndef handle_tls_event(cpu, data, size):\n    class TLSEvent(ct.Structure):\n        _fields_ = [(\"address\", ct.c_uint32),\n                    (\"port\", ct.c_uint16),\n                    (\"tls_version\", ct.c_uint16),\n                    (\"comm\", ct.c_char * 64),\n                    (\"message\", ct.c_uint8 * 64),\n                    (\"message_length\", ct.c_uint32),\n                    (\"pid\", ct.c_uint32),\n                    (\"is_read\", ct.c_uint32)]\n\n    # Map the data from kernel to the structure\n    tls_event = ct.cast(data, ct.POINTER(TLSEvent)).contents\n\n    # Get TLS information\n    pid_to_delete = None\n    master_secret = None\n    ciphersuite = None\n    bpf_map_tls_information = BPF_TLS_HANDLER[\"tls_information_cache\"]\n    for pid, tls_info in bpf_map_tls_information.items_lookup_batch():\n        if pid.value == tls_event.pid:\n            ciphersuite = tls_info.ciphersuite.decode(\"ascii\", \"ignore\")\n            master_secret = binascii.hexlify(tls_info.master_secret)\n            master_secret = master_secret.decode(\"ascii\", \"ignore\")\n            pid_to_delete = [pid]\n            break\n\n    # Delete pid from the eBPF map\n    if not pid_to_delete:\n        bpf_map_tls_information.items_delete_batch(pid_to_delete)\n\n    # Unpack the IPv4 destination address\n    addr = struct.pack(\"I\", tls_event.address)\n\n    # Discard empty content\n    if args.content and tls_event.message_length == 0:\n        return\n\n    # Display the TLS event\n    if args.directions:\n        if tls_event.is_read:\n            print(\"->\", end=\" \")\n        else:\n            print(\"<-\", end=\" \")\n    print(\"%s (%d)\" % (tls_event.comm.decode(\"ascii\", \"replace\"),\n                       tls_event.pid), end=\" \")\n    print(\"%s/%d\" % (socket.inet_ntop(socket.AF_INET, addr),\n                     socket.ntohs(tls_event.port)), end=\" \")\n\n    version = (tls_event.tls_version & 0xF) - 1\n    print(\"TLS1.%d %s\" % (version, ciphersuite))\n\n    # Display TLS secrets\n    if (args.secrets or args.write) and tls_event.tls_version == 0x303:\n        key_log = \"CLIENT_RANDOM 28071980 %s\\n\" % master_secret\n        if args.secrets:\n            print(\"\\n   %s\\n\" % key_log)\n        if args.write:\n            fd = open(\"%d-master_secret.log\" % pid.value, \"w\")\n            fd.write(key_log)\n            fd.close()\n\n    # Display the message content in hexadecimal\n    if args.content and tls_event.message_length:\n        hex_message = hexdump(tls_event.message[:tls_event.message_length],\n                              dump=True)\n        print(\"\\n   \", end=\"\")\n        print(hex_message.replace(\"\\n\", \"\\n   \"))\n        print()\n\n\ndef _tls_ebpf_programs(directions_bool, args_ssl_session_offset,\n                       args_ssl_cipher_offset, args_master_secret_offset,\n                       args_client_hello_offset, args_client_random_offset):\n    # Get SSL structures offsets\n    offsets = [str(offset) for offset in peetch.utils.get_offsets()]\n    ssl_session_offset, ssl_cipher_offset, master_secret_offset, \\\n        client_hello_offset, client_random_offset = offsets\n\n    if ssl_session_offset == ssl_cipher_offset and \\\n       ssl_cipher_offset == master_secret_offset and master_secret_offset == '0':  # noqa: E501\n        return None\n\n    if args_ssl_session_offset is not None:\n        ssl_session_offset = str(args_ssl_session_offset)\n\n    if args_ssl_cipher_offset is not None:\n        ssl_cipher_offset = str(args_ssl_cipher_offset)\n\n    if args_master_secret_offset is not None:\n        master_secret_offset = str(args_master_secret_offset)\n\n    if args_client_hello_offset is not None:\n        client_hello_offset = str(args.client_hello_offset)\n\n    if args_client_random_offset is not None:\n        client_random_offset = str(args.client_random_offset)\n\n    # Compile eBPF programs\n    ebpf_programs = BPF_TLS_PROGRAM_SOURCE.replace(\"DIRECTIONS\",\n                                                   directions_bool)\n    ebpf_programs = ebpf_programs.replace(\"SSL_SESSION_OFFSET\",\n                                          ssl_session_offset)\n    ebpf_programs = ebpf_programs.replace(\"MASTER_SECRET_OFFSET\",\n                                          master_secret_offset)\n    ebpf_programs = ebpf_programs.replace(\"SSL_CIPHER_OFFSET\",\n                                          ssl_cipher_offset)\n    ebpf_programs = ebpf_programs.replace(\"CLIENT_HELLO_OFFSET\",\n                                          client_hello_offset)\n    ebpf_programs = ebpf_programs.replace(\"CLIENT_RANDOM_OFFSET\",\n                                          client_random_offset)\n\n    return ebpf_programs\n\n\ndef tls_command(args):\n    global BPF_TLS_HANDLER\n\n    # Process arguments\n    if args.content:\n        args.directions = True\n\n    directions_bool = \"1\"\n    if args.directions:\n        directions_bool = \"0\"\n\n    ebpf_programs = _tls_ebpf_programs(directions_bool,\n                                       args.ssl_session_offset,\n                                       args.ssl_cipher_offset,\n                                       args.master_secret_offset,\n                                       args.client_hello_offset,\n                                       args.client_random_offset)\n    if ebpf_programs is None:\n        print(\"ERROR: cannot guess SSL offsets!\", file=sys.stderr)\n        sys.exit(1)\n    bpf_handler = BPF(text=ebpf_programs)\n    BPF_TLS_HANDLER = bpf_handler\n\n    # Attach the probes\n    try:\n        bpf_handler.attach_uprobe(name=\"ssl\",\n                                  sym=\"SSL_write\", fn_name=\"SSL_write\")\n        bpf_handler.attach_uprobe(name=\"ssl\",\n                                  sym=\"SSL_read\", fn_name=\"SSL_read\")\n        bpf_handler.attach_uretprobe(name=\"ssl\",\n                                     sym=\"SSL_read\", fn_name=\"SSL_read_ret\")\n    except Exception:\n        print(\"tls - cannot attach to eBPF probes!\")\n        sys.exit()\n\n    def handle_tls_event(cpu, data, size):\n        class TLSEvent(ct.Structure):\n            _fields_ = [(\"address\", ct.c_uint32),\n                        (\"port\", ct.c_uint16),\n                        (\"tls_version\", ct.c_uint16),\n                        (\"comm\", ct.c_char * 64),\n                        (\"message\", ct.c_uint8 * 64),\n                        (\"message_length\", ct.c_uint32),\n                        (\"pid\", ct.c_uint32),\n                        (\"is_read\", ct.c_uint32)]\n\n        # Map the data from kernel to the structure\n        tls_event = ct.cast(data, ct.POINTER(TLSEvent)).contents\n\n        # Get TLS information\n        pid_to_delete = None\n        master_secret = None\n        ciphersuite = None\n        client_random = None\n        bpf_map_tls_information = bpf_handler[\"tls_information_cache\"]\n        for pid, tls_info in bpf_map_tls_information.items_lookup_batch():\n            if pid.value == tls_event.pid:\n                ciphersuite = tls_info.ciphersuite.decode(\"ascii\", \"ignore\")\n                master_secret = binascii.hexlify(tls_info.master_secret)\n                master_secret = master_secret.decode(\"ascii\", \"ignore\")\n                client_random = binascii.hexlify(tls_info.client_random)\n                client_random = client_random.decode(\"ascii\", \"ignore\")\n                pid_to_delete = [pid]\n                break\n\n        # Delete pid from the eBPF map\n        if not pid_to_delete:\n            bpf_map_tls_information.items_delete_batch(pid_to_delete)\n\n        # Unpack the IPv4 destination address\n        addr = struct.pack(\"I\", tls_event.address)\n\n        # Discard empty content\n        if args.content and tls_event.message_length == 0:\n            return\n\n        # Display the TLS event\n        if args.directions:\n            if tls_event.is_read:\n                print(\"->\", end=\" \")\n            else:\n                print(\"<-\", end=\" \")\n        print(\"%s (%d)\" % (tls_event.comm.decode(\"ascii\", \"replace\"),\n                           tls_event.pid), end=\" \")\n        print(\"%s/%d\" % (socket.inet_ntop(socket.AF_INET, addr),\n                         socket.ntohs(tls_event.port)), end=\" \")\n\n        version = (tls_event.tls_version & 0xF) - 1\n        print(\"TLS1.%d %s\" % (version, ciphersuite))\n\n        # Display TLS secrets\n        if (args.secrets or args.write) and tls_event.tls_version == 0x303:\n            key_log = \"CLIENT_RANDOM %s %s\\n\" % (client_random, master_secret)\n            if args.secrets:\n                print(\"\\n   %s\\n\" % key_log)\n            if args.write:\n                fd = open(\"%d-master_secret.log\" % pid.value, \"w\")\n                fd.write(key_log)\n                fd.close()\n\n        # Display the message content in hexadecimal\n        if args.content and tls_event.message_length:\n            hex_message = hexdump(tls_event.message[:tls_event.message_length],\n                                  dump=True)\n            print(\"\\n   \", end=\"\")\n            print(hex_message.replace(\"\\n\", \"\\n   \"))\n            print()\n\n    bpf_handler[\"tls_events\"].open_perf_buffer(handle_tls_event)\n    while True:\n        try:\n            bpf_handler.perf_buffer_poll()\n        except KeyboardInterrupt:\n            sys.exit()\n\n\ndef proxy_command(args):\n    # Compile eBPF programs\n    ebpf_programs = BPF_PROXY_PROGRAM_SOURCE.replace(\"PEETCH_PROXY_PID\",\n                                                     str(os.getpid()))\n    bpf_handler = BPF(text=ebpf_programs)\n    peetch.globals.BPF_HANDLER = bpf_handler\n\n    # Load the eBPF function\n    connect_function = bpf_handler.load_func(\"connect_v4_prog\",\n                                             prog_type=BPFProgType.CGROUP_SOCK_ADDR,  # noqa: E501\n                                             attach_type=BPFAttachType.CGROUP_INET4_CONNECT)  # noqa: E501\n\n    # Attach the eBPF function to the default cgroup\n    cgroup_fd = os.open(\"/sys/fs/cgroup\", os.O_RDONLY)\n    bpf_handler.attach_func(connect_function, cgroup_fd,\n                            BPFAttachType.CGROUP_INET4_CONNECT)\n\n    # Attach the SSL_* uprobes\n    ebpf_programs = _tls_ebpf_programs(\"1\", None, None, None, None, None)\n    if ebpf_programs is None:\n        print(\"ERROR: cannot guess SSL offsets!\", file=sys.stderr)\n        sys.exit(1)\n\n    bpf_tls_handler = BPF(text=ebpf_programs)\n    peetch.globals.BPF_TLS_HANDLER = bpf_tls_handler\n    try:\n        bpf_tls_handler.attach_uprobe(name=\"ssl\",\n                                      sym=\"SSL_write\", fn_name=\"SSL_write\")\n        bpf_tls_handler.attach_uprobe(name=\"ssl\",\n                                      sym=\"SSL_read\", fn_name=\"SSL_read\")\n        bpf_tls_handler.attach_uretprobe(name=\"ssl\",\n                                         sym=\"SSL_read\", fn_name=\"SSL_read_ret\")  # noqa: E501\n    except Exception:\n        print(\"proxy - cannot attach to eBPF SSL_* uprobes!\")\n        sys.exit()\n\n    print(\"[-] Proxying OpenSSL traffic\")\n\n    # Setup the exit handler\n    atexit.register(exit_handler_proxy, bpf_handler,\n                    connect_function, cgroup_fd)\n\n    # Start the proxy\n    try:\n        asyncio.run(all_tasks(args.debug))\n    except KeyboardInterrupt:\n        pass\n\n\ndef main():\n    global args\n    argv = sys.argv[1:]\n\n    # Parsing arguments\n    parser = argparse.ArgumentParser(description=\"peetch - an eBPF playground\")\n    subparser = parser.add_subparsers()\n    parser.set_defaults(func=lambda args: parser.print_help())\n\n    # Prepare the 'dump' subcommand\n    dump_parser = subparser.add_parser(\"dump\",\n                                       help=\"Sniff packets with eBPF\")\n    dump_parser.add_argument(\"--raw\", action=\"store_true\",\n                             help=\"display packets only\")\n    dump_parser.add_argument(\"--write\", type=str,\n                             help=\"pcapng filename\")\n    dump_parser.add_argument(\"--interface\", type=str,\n                             help=\"interface name\", default=str(conf.iface))\n    dump_parser.set_defaults(func=dump_command)\n\n    # Prepare the 'tls' subcommand\n    tls_parser = subparser.add_parser(\"tls\",\n                                      help=\"Identify processes that uses TLS\")\n    tls_parser.add_argument(\"--directions\", action=\"store_true\",\n                            help=\"display read & write calls\")\n    tls_parser.add_argument(\"--content\", action=\"store_true\",\n                            help=\"display buffers content\")\n    tls_parser.add_argument(\"--secrets\", action=\"store_true\",\n                            help=\"display TLS secrets\")\n    tls_parser.add_argument(\"--write\", action=\"store_true\",\n                            help=\"write TLS secrets to files\")\n    tls_parser.add_argument(\"--ssl_session_offset\",\n                            help=\"offset to the ssl_session_t structure\")\n    tls_parser.add_argument(\"--master_secret_offset\",\n                            help=\"offset to the master secret in an ssl_session_t structure\")  # noqa: E501\n    tls_parser.add_argument(\"--ssl_cipher_offset\",\n                            help=\"offset to the ssl_cipher structure in an ssl_session_t structure\")  # noqa: E501\n    tls_parser.add_argument(\"--client_hello_offset\",\n                            help=\"offset to the CLIENTHELLO_MSG structure in an ssl structure\")  # noqa: E501\n    tls_parser.add_argument(\"--client_random_offset\",\n                            help=\"offset to the client random in an CLIENTHELLO_MSG structure\")  # noqa: E501\n    tls_parser.set_defaults(func=tls_command)\n\n    # Prepare the 'proxy' subcommand\n    proxy_parser = subparser.add_parser(\"proxy\",\n                                        help=\"Automatically intercept TLS connections\")  # noqa: E501\n    proxy_parser.add_argument(\"--debug\", action=\"store_true\",\n                              help=\"display debug information\")\n    proxy_parser.set_defaults(func=proxy_command)\n\n    # Print the Help message when no arguments are provided\n    if not argv:\n        parser.print_help(sys.stderr)\n        sys.exit(1)\n\n    # Call the sub-command\n    args = parser.parse_args(argv)\n    args.func(args)\n"
  },
  {
    "path": "peetch/__main__.py",
    "content": "#!/usr/bin/env python3\n# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nfrom . import main\n\nmain()\n"
  },
  {
    "path": "peetch/c_utils/libssl.c",
    "content": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <arpa/inet.h>\n#include <netinet/in.h>\n#include <sys/socket.h>\n\n#include <openssl/ssl.h>\n\n#define STRUCTURE_SIZE 8192\n\nstruct libssl_offsets_t {\n  uint64_t ssl_session;\n  uint64_t ssl_cipher;\n  uint64_t master_secret;\n  uint64_t client_hello;\n  uint64_t client_random;\n};\n\n\nstruct libssl_offsets_t libssl_offsets(char *ip4_address, uint16_t port) {\n  struct libssl_offsets_t offsets = { .ssl_session = 0,\n                                      .ssl_cipher = 0, .master_secret = 0};\n\n  // Create the SSL context and set the TLS version\n  const SSL_METHOD *method = TLS_client_method();\n  SSL_CTX *ctx = SSL_CTX_new(method);\n\n  int ret = SSL_CTX_set_max_proto_version(ctx, TLS1_2_VERSION);\n  if (ret < 0) {\n    printf(\"SSL_CTX_set_max_proto_version() error - %d\\n\", ret);\n    return offsets;\n  }\n\n  // Set up a TLS connection to get the SSL session structure\n  SSL *ssl = SSL_new(ctx);\n\n  int fd = socket(AF_INET, SOCK_STREAM, 0);\n  if (fd < 0) {\n    printf(\"socket() error - %d\\n\", fd);\n    return offsets;\n  }\n\n  struct sockaddr_in addr;\n  addr.sin_family = AF_INET;\n  addr.sin_port = htons(port);\n  ret = inet_aton(ip4_address, (struct in_addr*) &addr.sin_addr.s_addr);\n  if (ret < 0) {\n    printf(\"inet_aton() error - %d\\n\", fd);\n    return offsets;\n  }\n\n  ret = connect(fd, (struct sockaddr*) &addr, sizeof(addr));\n  if (ret < 0) {\n    printf(\"connect() error - %d\\n\", fd);\n    return offsets;\n  }\n\n  ret = SSL_set_fd(ssl, fd);\n  if (ret < 0) {\n    printf(\"SSL_set_fd() error - %d\\n\", fd);\n    return offsets;\n  }\n\n  ret = SSL_connect(ssl);\n  if (ret < 0) {\n    printf(\"SSL_connect() error - %d\\n\", fd);\n    return offsets;\n  }\n\n  // SSL_SESSION* offset\n  SSL_SESSION *session = SSL_get_session(ssl);\n  for (uint64_t i = 0x000; i < STRUCTURE_SIZE; i++) {\n    uint64_t value = (uint64_t) ssl + i;\n    uint64_t *ptr = (uint64_t*) value;\n    if ((uint64_t) *ptr == (uint64_t) session) {\n      offsets.ssl_session = i;\n      break;\n    }\n  }\n\n  // SSL_CIPHER* offset\n  const SSL_CIPHER *cipher = SSL_get_current_cipher(ssl);\n  for (uint64_t i = 0x000; i < STRUCTURE_SIZE; i++) {\n    uint64_t value = (uint64_t) session + i;\n    uint64_t *ptr = (uint64_t*) value;\n    if ((uint64_t) *ptr == (uint64_t) cipher) {\n      offsets.ssl_cipher = i;\n      break;\n    }\n  }\n\n  // TLS 1.2 MASTER_SECRET offset\n  uint8_t master_secret[48];\n  ret = SSL_SESSION_get_master_key(session,\n                                  (unsigned char*)&master_secret, sizeof(master_secret));\n  if (ret != 48) {\n    printf(\"SSL_SESSION_get_master_key() error - %d\\n\", fd);\n    return offsets;\n  }\n  for (uint64_t i=0x000; i < STRUCTURE_SIZE; i++) {\n    uint64_t value = (uint64_t) session + i;\n    uint64_t *ptr = (uint64_t*) value;\n    value = (uint64_t) session + i + 47;\n    uint64_t *ptr_end = (uint64_t*) value;\n    if ((*ptr & 0xFF) == master_secret[0] && \\\n        (*ptr_end & 0xFF) == master_secret[47]) {\n      offsets.master_secret = i;\n      break;\n    }\n  }\n\n  // Client Random offset\n  uint8_t client_random[32];\n  offsets.client_hello = 0;\n  ret = SSL_get_client_random(ssl, (unsigned char*)&client_random, sizeof(client_random));\n  if (ret != 32) {\n    printf(\"SSL_get_client_random() error - %d\\n\", fd);\n    return offsets;\n  }\n  for (uint64_t i=0; i < STRUCTURE_SIZE; i++) {\n    if (offsets.client_hello != 0)\n      break;\n\n    uint64_t value = (uint64_t) ssl + i;\n    uint64_t *ptr = (uint64_t*) value;\n\n    if (*ptr) {\n      for (uint8_t j=0; j < sizeof(STRUCTURE_SIZE) ; j++) {\n          uint8_t *new_ptr = (uint8_t*) ptr + j;\n          if ((new_ptr[0] & 0xFF) == client_random[0] && \\\n              (new_ptr[31] & 0xFF) == client_random[31]) {\n            offsets.client_hello = i;\n            offsets.client_random = j;\n            break;\n          }\n      }\n    }\n\n  }\n\n  return offsets;\n}\n\n\nint main() {\n /*\n Compile it with:\n cc -o libssl_offsets libssl.c -lssl\n */\n  struct libssl_offsets_t offsets = libssl_offsets(\"1.1.1.1\", 443);\n  printf(\"--ssl_session_offset=0x%lx\\n\", offsets.ssl_session);\n  printf(\"--ssl_cipher_offset=0x%lx\\n\", offsets.ssl_cipher);\n  printf(\"--master_secret_offset=0x%lx\\n\", offsets.master_secret);\n  printf(\"--client_hello=0x%lx\\n\", offsets.client_hello);\n  printf(\"--client_random=0x%lx\\n\", offsets.client_random);\n\n  return EXIT_SUCCESS;\n}\n"
  },
  {
    "path": "peetch/ebpf_programs/peetch_kprobes.c",
    "content": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/if_ether.h>\n#include <linux/ip.h>\n#include <linux/tcp.h>\n\n\n#include <uapi/linux/pkt_cls.h>\n#include <uapi/linux/bpf.h>\n#include <linux/sched.h>\n#include <net/sock.h>\n\n\nstruct key_t {\n  u32 dst;\n  u32 src;\n};\n\nstruct data_t {\n  u32 pid;\n  char name[TASK_COMM_LEN];\n};\n\nBPF_HASH(pid_cache, struct key_t, struct data_t);\n\nBPF_PERF_OUTPUT(skb_events);\n\nint process_frame(struct __sk_buff *skb) {\n  // Data accessors\n  unsigned char *data = (void *)(long)skb->data;\n  unsigned char *data_end = (void *)(long)skb->data_end;\n\n  // Mapping data to the Ethernet and IP headers\n  struct ethhdr *eth = (struct ethhdr *)data;\n  struct iphdr *iph = (struct iphdr*) (data + sizeof(struct ethhdr));\n\n  // Simple length check\n  if ((data + sizeof(struct ethhdr) + sizeof(struct iphdr)) > data_end)\n    return TC_ACT_OK;\n\n  // Discard everything but IPv4\n  if (ntohs(eth->h_proto) != ETH_P_IP)\n    return TC_ACT_OK;\n\n  // Discard everything but TCP\n  if (iph->protocol != IPPROTO_TCP)\n    return TC_ACT_OK;\n\n  // Retrieve the PID and the process name from the IP addresses\n  struct key_t key = { .dst = iph->daddr, .src = iph->saddr };\n  struct data_t *value = (struct data_t *) pid_cache.lookup(&key);\n  if (value == NULL) {\n    key.dst = iph->saddr;\n    key.src = iph->daddr;\n    value = (struct data_t *) pid_cache.lookup(&key);\n    if (value == NULL)\n      return TC_ACT_OK;\n  }\n\n  // Check the PID\n  if (value->pid == 0)\n    return TC_ACT_OK;\n\n  struct data_t tmp;\n  __builtin_memset(&tmp, 0, sizeof(tmp));     // it makes the eBPF verifier happy!\n  tmp.pid = value->pid;\n  for (u8 i=0; i < TASK_COMM_LEN; i++)\n    tmp.name[i] = value->name[i];\n\n  skb_events.perf_submit_skb(skb, skb->len, &tmp, sizeof(tmp));\n\n  return TC_ACT_OK;\n}\n\nint kprobe_security_sk_classify_flow(struct pt_regs *ctx, struct sock *sk, struct flowi *fl) {\n  // Discard everything but IPv4\n  if (sk->sk_family != AF_INET)\n    return 0;\n\n  // Extract IPv4 related structures\n  union flowi_uli uli;\n  struct flowi4 ip4;\n  bpf_probe_read(&ip4, sizeof(ip4), &fl->u.ip4);\n  bpf_probe_read(&uli, sizeof(uli), &ip4.uli);\n\n  // Get IP addresses and ports\n  struct key_t key;\n  struct data_t data;\n\n  // it makes the eBPF verifier happy!\n  __builtin_memset(&key, 0, sizeof(key));\n  __builtin_memset(&data, 0, sizeof(data));\n\n  bpf_probe_read(&key.src,\n                 sizeof(sk->__sk_common.skc_daddr),\n                 &sk->__sk_common.skc_daddr);\n  bpf_probe_read(&key.dst,\n                 sizeof(sk->__sk_common.skc_rcv_saddr),\n                 &sk->__sk_common.skc_rcv_saddr);\n\n  // Get and store the PID\n  u64 id = bpf_get_current_pid_tgid();\n  data.pid = id >> 32;\n\n  // Get and store the process name\n  bpf_get_current_comm(data.name, sizeof(data.name));\n\n  // Store data\n  pid_cache.update(&key, &data);\n\n  return 0;\n}\n"
  },
  {
    "path": "peetch/ebpf_programs/peetch_proxy.c",
    "content": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/bpf.h>\n#include <linux/in.h>\n\nstruct data_t {\n  u32 pid;\n  char name[64];\n  u32 ip;\n  u32 port;\n};\n\nBPF_HASH(pid_cache, u64);\n\nBPF_HASH(destination_cache, u16, struct data_t);\n\nint connect_v4_prog(struct bpf_sock_addr *ctx) {\n  struct data_t data;\n\n  // Get and store the PID\n  u64 id = bpf_get_current_pid_tgid();\n  data.pid = id >> 32;\n\n  // Do not intercept connection from peetch itself\n  if (PEETCH_PROXY_PID == data.pid)\n    return 1;\n\n  // Do not intercept well known TCP services\n  if (ctx->user_port == bpf_htons(53)) // DNS\n    return 1;\n\n  // Check if the PID is in the cache\n  u64 *tmp_id = pid_cache.lookup((u64*) &id);\n  if (tmp_id == NULL)\n    return 1;\n  if (*tmp_id != id)\n    return 1;\n\n  // Get and store the process name\n  bpf_get_current_comm(data.name, 64);\n\n  // Rewrite the source port\n  struct sockaddr_in sa = {};\n\tsa.sin_family = AF_INET;\n  u16 new_port = bpf_htons(data.pid & 0xFFFF); // lower part of the PID will be used as the TCP source port\n  sa.sin_port = new_port;\n  sa.sin_addr.s_addr = bpf_htonl(0x7f000001); // 127.0.0.1\n\n\tif (bpf_bind(ctx, (struct sockaddr *) &sa, sizeof(sa)) != 0)\n\t\treturn 0;\n\n  // Get and store the real destination IPv4 address and port\n  data.ip = ctx->user_ip4;\n  data.port = ctx->user_port;\n\n  // Store the connection data into the cache\n  destination_cache.update(&new_port, &data);\n\n  // Divert the connection to peetch proxy\n  ctx->user_ip4 = 0x0100007f;\n\tctx->user_port = bpf_htons(2807);\n\n  /*\n  Note:\n  - 1: accept\n  - 0: discard\n  */\n  return 1;\n}\n\nTRACEPOINT_PROBE(syscalls, sys_enter_openat) {\n  #define _PATH_MAX 128\n  char filename[_PATH_MAX + 1];\n\n  // Retrieve the filename\n  long ret = bpf_probe_read((void*)&filename, _PATH_MAX, (void*)args->filename);\n   if (ret != 0) {\n     //bpf_trace_printk(\"sys_enter_openat() - bpf_probe_read() failed\\n\");\n     return 0;\n   }\n\n  // Check if the filename contains \"libssl.so\"\n  for (u16 i=8; i < _PATH_MAX; i++) {\n    if (filename[i-8] == 'l' && filename[i-7] == 'i'  && filename[i-6] == 'b' && filename[i-5] == 's' &&\n        filename[i-4] == 's' && filename[i-3] == 'l'  && filename[i-2] == '.' && filename[i-1] == 's') {\n\n      // Get and store the PID\n      u64 id = bpf_get_current_pid_tgid();\n      u64 pid = id >> 32;\n      pid_cache.update(&id, &id);\n      break;\n    }\n  }\n\n  return 0;\n}\n"
  },
  {
    "path": "peetch/ebpf_programs/peetch_uprobes.c",
    "content": "// SPDX-License-Identifier: GPL-2.0+\n// Guillaume Valadon <gvaladon@quarkslab.com>\n\n#include <linux/in.h>\n#include <linux/ptrace.h>\n\n\n// Data structure sent to userland\nstruct tls_event_t {\n    u32 addr;\n    u16 port;\n    u16 tls_version;\n    #define COMM_MAX_LEN 64\n    char comm[COMM_MAX_LEN];\n    #define MESSAGE_MAX_LEN 64\n    u8 message[MESSAGE_MAX_LEN];\n    u32 message_length;\n    u32 pid;\n    u32 is_read;\n};\nBPF_PERF_OUTPUT(tls_events);\n\n\n// Store SSL_* buffer information\nstruct SSL_buffer_t {\n    u64 ptr;\n    u32 length;\n    u32 tls_version;\n    u32 is_read;\n};\nBPF_HASH(SSL_read_buffers, u32, struct SSL_buffer_t);\n\n\n// Store connect information indexed by PID\nBPF_HASH(pid_cache, u32);\n\n\n// TLS information\nstruct TLS_information_t {\n    u16 tls_version;\n    #define CIPHERSUITE_MAX_LEN 32\n    char ciphersuite[CIPHERSUITE_MAX_LEN];\n    #define MASTER_SECRET_MAX_LEN 48\n    u8 master_secret[MASTER_SECRET_MAX_LEN];\n    #define CLIENT_RANDOM_MAX_LEN 32\n    u8 client_random[CLIENT_RANDOM_MAX_LEN];\n};\nBPF_HASH(tls_information_cache, u32, struct TLS_information_t);\n\n\nTRACEPOINT_PROBE(syscalls, sys_enter_connect) {\n    // Retrieve the sockaddr_in structure\n    struct sockaddr_in addr_in;\n    long ret = bpf_probe_read((void*)&addr_in, sizeof(addr_in), args->uservaddr);\n    if (ret != 0) {\n        bpf_trace_printk(\"sys_enter_connect() - bpf_probe_read() failed\\n\");\n        return 0;\n    }\n\n    // Discard everything but IPv4\n    if (addr_in.sin_family != AF_INET)\n        return 0;\n\n    // Retrieve the PID\n    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;\n\n    // Store a TLS event in the pid_cache\n    struct tls_event_t event = { .port = addr_in.sin_port,\n                                 .addr = addr_in.sin_addr.s_addr};\n    pid_cache.update(&pid, (u64*)&event);\n\n    return 0;\n}\n\n\n// Dummy openssl ssl_st structure\nstruct ssl_st {\n    int version;\n};\n\n\nstatic u16 get_tls_version(void *ssl_st_ptr) {\n    // Extract the TLS version from a struct ssl_str pointer\n    struct ssl_st ssl;\n\n    long ret = bpf_probe_read(&ssl, sizeof(ssl), ssl_st_ptr);\n    if (ret != 0) {\n        bpf_trace_printk(\"get_tls_version() - bpf_probe_read() failed\\n\");\n        return -1;\n    }\n\n    return ssl.version;\n}\n\n\nstatic void parse_session(struct pt_regs *ctx, u16 tls_version) {\n    // Parse a struct sl_session_st pointer and send\n    // data to userspace\n\n    // TLS information sent to userspace\n    struct TLS_information_t tls_information;\n    __builtin_memset(&tls_information, 0, sizeof(tls_information)); // it makes the eBPF verifier happy!\n    tls_information.tls_version = tls_version;\n\n    // Get a ssl_st pointer\n    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);\n\n    // Get a ssl_session_st pointer\n    u64 *ssl_session_st_ptr = (u64 *) (ssl_st_ptr + SSL_SESSION_OFFSET);\n\n    u64 address;\n    long ret = bpf_probe_read(&address, sizeof(address), ssl_session_st_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #1 - bpf_probe_read() failed\\n\");\n\n    // Access the TLS 1.2 master secret\n    void *ms_ptr = (void *) (address + MASTER_SECRET_OFFSET);\n    ret = bpf_probe_read(&tls_information.master_secret,\n                              sizeof(tls_information.master_secret), ms_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #2 - bpf_probe_read() failed\\n\");\n\n    // Get a ssl_cipher_st pointer\n    void *ssl_cipher_st_ptr = (void *) (address + SSL_CIPHER_OFFSET);\n    ret = bpf_probe_read(&address, sizeof(address), ssl_cipher_st_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #3 - bpf_probe_read() failed\\n\");\n\n    // Get the SSL_cipher_st point to the name member\n    ssl_cipher_st_ptr = (void *) (address + 8);\n    ret = bpf_probe_read(&address, sizeof(address), ssl_cipher_st_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #4 - bpf_probe_read() failed\\n\");\n\n    // Access the TLS ciphersuite\n    void *cs_ptr = (void *) address;\n    ret = bpf_probe_read(&tls_information.ciphersuite,\n                              sizeof(tls_information.ciphersuite), cs_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #5 - bpf_probe_read() failed\\n\");\n\n    // Retrieve the Client Random\n    void* client_hello_ptr = (void *) (ssl_st_ptr + CLIENT_HELLO_OFFSET);\n    ret = bpf_probe_read(&address, sizeof(address), client_hello_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #6 - bpf_probe_read() failed\\n\");\n\n    u8 client_random[CLIENT_RANDOM_MAX_LEN + CLIENT_RANDOM_OFFSET];\n    ret = bpf_probe_read(client_random, sizeof(client_random), client_hello_ptr);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #7 - bpf_probe_read() failed\\n\");\n\n    ret = bpf_probe_read(&tls_information.client_random, sizeof(tls_information.client_random), client_random + CLIENT_RANDOM_OFFSET);\n    if (ret != 0)\n        bpf_trace_printk(\"parse_session() #8 - bpf_probe_read() failed\\n\");\n\n    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;\n    tls_information_cache.update(&pid, &tls_information);\n}\n\n\nstatic int SSL_read_write(struct pt_regs *ctx, u16 tls_version, struct SSL_buffer_t *buffer) {\n    // A buffer is needed\n    if (buffer == NULL)\n        return 0;\n\n    // Retrieve connect() information for PID\n    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;\n    struct tls_event_t *event = (struct tls_event_t*) pid_cache.lookup(&pid);\n    if (event == NULL) {\n    \n    \t//get ppid to check if it is a child of a known process \n    \tstruct task_struct *task;\n\t\ttask = (struct task_struct *)bpf_get_current_task();\n\t\tpid = task->real_parent->tgid;\n\t\t\n\t\tevent = (struct tls_event_t*) pid_cache.lookup(&pid);\n    \tif(event == NULL)\n    \t\treturn 0;\n    }\n\n    // Build a new TLS event and fill it\n    struct tls_event_t new_event;\n\n    bpf_get_current_comm(&new_event.comm, COMM_MAX_LEN);\n    new_event.pid = pid;\n    new_event.port = event->port;\n    new_event.addr = event->addr;\n    new_event.is_read = buffer->is_read;\n    new_event.tls_version = tls_version;\n\n    long ret = bpf_probe_read(&new_event.message,\n                             sizeof(new_event.message), (void*) buffer->ptr);\n    if (ret != 0) {\n        bpf_trace_printk(\"SSL_read_write() - bpf_probe_read() failed\\n\");\n        return 0;\n    }\n    new_event.message_length = buffer->length;\n\n    // Send the event to userland\n    tls_events.perf_submit(ctx, &new_event, sizeof(new_event));\n\n    // Flush the PID cache\n    if (DIRECTIONS)  // this will be replaced by a boolean in Python\n        pid_cache.delete(&pid);\n\n    return 0;\n}\n\n\nint SSL_read(struct pt_regs *ctx) {\n    // Retrieve the PID\n    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;\n\n    // Store a SSL read buffer information in the cache\n    struct SSL_buffer_t buffer;\n    __builtin_memset(&buffer, 0, sizeof(buffer));\n    buffer.ptr = PT_REGS_PARM2(ctx);\n\n    // Get TLS version\n    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);\n    buffer.tls_version = get_tls_version(ssl_st_ptr);\n\n    SSL_read_buffers.update(&pid, &buffer);\n\n    return 0;\n}\n\n\nint SSL_read_ret(struct pt_regs *ctx) {\n    // Discard if nothing was received\n    int buffer_length = PT_REGS_RC(ctx);\n    if (buffer_length == -1)\n        return 0;\n\n    // Retrieve SSL read buffers information for PID\n    u32 pid = bpf_get_current_pid_tgid() & 0xFFFFFFFF;\n    struct SSL_buffer_t *buffer = (struct SSL_buffer_t*) SSL_read_buffers.lookup(&pid);\n    if (buffer == NULL)\n        return 0;\n\n    // Add buffer information\n    buffer->length = buffer_length;\n    buffer->is_read = 1;\n\n    long ret = SSL_read_write(ctx, buffer->tls_version, buffer);\n    SSL_read_buffers.delete(&pid);\n\n    return ret;\n}\n\n\nint SSL_write(struct pt_regs *ctx) {\n    // Retrieve the buffer information\n    struct SSL_buffer_t buffer;\n\n    buffer.ptr = PT_REGS_PARM2(ctx);\n    buffer.length = PT_REGS_PARM3(ctx);\n    buffer.is_read = 0;\n\n    // Get TLS version\n    void *ssl_st_ptr = (void *) PT_REGS_PARM1(ctx);\n    u16 tls_version = get_tls_version(ssl_st_ptr);\n\n    parse_session(ctx, tls_version);\n\n    return SSL_read_write(ctx, tls_version, &buffer);\n}\n"
  },
  {
    "path": "peetch/globals.py",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nBPF_HANDLER = None\nBPF_TLS_HANDLER = None\nPACKETS_CAPTURED = []\nTLS_INFORMATION = {}\n"
  },
  {
    "path": "peetch/proxy.py",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport asyncio\nimport binascii\nimport ctypes as ct\nimport socket\nimport struct\nimport sys\nimport time\n\nfrom scapy.all import sniff, IP, TCP, conf\n\nimport peetch.globals\n\n\ndef retrieve_client_information(bpf_handler, port_src):\n    \"\"\"\n    Get client information from eBPF maps\n    \"\"\"\n\n    process_name, process_pid, ip_dst, port_dst = [None] * 4\n    bpf_map_destination_cache = bpf_handler[\"destination_cache\"]\n\n    destination_key_to_delete = None\n\n    for destination_key, destination_data in bpf_map_destination_cache.items_lookup_batch():  # noqa: E501\n        process_pid = destination_data.pid\n        process_name = destination_data.name.decode(\"ascii\", \"replace\")\n\n        # Retrieve destination IP and port\n        address_packed = struct.pack(\"I\", destination_data.ip)\n        ip_dst = socket.inet_ntop(socket.AF_INET, address_packed)\n        port_dst = socket.ntohs(destination_data.port)\n\n        if socket.ntohs(destination_key.value) == port_src:\n            ct_array = ct.c_uint16 * 1\n            destination_key_to_delete = ct_array(destination_key)\n            break\n\n    if destination_key_to_delete:\n        bpf_map_destination_cache.items_delete_batch(destination_key_to_delete)\n\n    return process_name, process_pid, ip_dst, port_dst\n\n\ndef retrieve_tls_information(bpf_handler, process_pid):\n    \"\"\"\n    Get TLS information from eBPF maps\n    \"\"\"\n    tls_version, ciphersuite, client_random, master_secret = [None] * 4\n\n    retries = 5\n    pid_to_delete = None\n    bpf_map_tls_information = bpf_handler[\"tls_information_cache\"]\n    while pid_to_delete is None and retries:\n        retries -= 1\n        for pid, tls_info in bpf_map_tls_information.items_lookup_batch():\n            if pid.value == process_pid:\n                ciphersuite = tls_info.ciphersuite.decode(\"ascii\", \"ignore\")\n                master_secret = binascii.hexlify(tls_info.master_secret)\n                master_secret = master_secret.decode(\"ascii\", \"ignore\")\n                client_random = binascii.hexlify(tls_info.client_random)\n                client_random = client_random.decode(\"ascii\", \"ignore\")\n                tls_version = (tls_info.tls_version & 0xF) - 1\n                if len(ciphersuite):\n                    ct_array = ct.c_uint * 1\n                    pid_to_delete = ct_array(pid)\n                    break\n        #time.sleep(0.005)\n\n    # Delete pid from the eBPF map\n    if pid_to_delete:\n        bpf_map_tls_information.items_delete_batch(pid_to_delete)\n\n    return tls_version, ciphersuite, client_random, master_secret\n\n\nasync def dots():\n    \"\"\"\n    print dots\n    \"\"\"\n    while True:\n        await asyncio.sleep(0.5)\n        print(\".\", end=\"\", flush=True)\n\n\ndef decrypt_messages(tls_information, packets):\n    \"\"\"\n    Decrypt and display messages\n    \"\"\"\n\n    tls_version = tls_information.get(\"version\", sys.maxsize)\n    if tls_version < 3:\n        for p in sniff(offline=packets):\n            if TLSApplicationData in p:  # noqa: F821\n                print()\n                p[TLSApplicationData].show()  # noqa: F821\n\n\nasync def handle_client(local_reader, local_writer):\n    \"\"\"\n    Proxy a new client connection\n    \"\"\"\n\n    # Retrieve source IP and port used to connect to the proxy\n    ip_src, port_src = local_reader._transport.get_extra_info(\"peername\")\n\n    # Retrieve process information, and destination IP and port\n    tmp = retrieve_client_information(peetch.globals.BPF_HANDLER, port_src)\n    process_name, process_pid, ip_dst, port_dst = tmp\n\n    if process_name is None:\n        print(\"[!] Did not find the real destination\")\n        local_writer.close()\n        return\n\n    print(\"\", flush=True)\n    print(f\"\\r[+] Intercepting traffic from {process_name}/{process_pid}\", end=\"\")  # noqa: E501\n    print(f\" to {ip_dst}/{port_dst} via {ip_src}/{port_src}\")\n\n    try:\n        # Connect to the real destination and copy data between sockets\n        tmp = await asyncio.open_connection(ip_dst, port_dst)\n        remote_reader, remote_writer = tmp\n        pipe1 = pipe(local_reader, remote_writer, process_pid,\n                     \"-->\", ip_src, ip_dst, port_src, port_dst)\n        pipe2 = pipe(remote_reader, local_writer, process_pid,\n                     \"<--\", ip_dst, ip_src, port_dst, port_src)\n        await asyncio.gather(pipe1, pipe2)\n\n        # Decrypt and display TLS messages\n        decrypt_messages(peetch.globals.TLS_INFORMATION,\n                         peetch.globals.PACKETS_CAPTURED)\n\n        # Reset global variables\n        conf.tls_nss_keys = {}\n        peetch.globals.TLS_INFORMATION = {}\n        peetch.globals.PACKETS_CAPTURED = []\n    except ConnectionResetError as e:\n        print(f\"   {e}\")\n    finally:\n        local_writer.close()\n\n\nasync def pipe(reader, writer, pid, direction, ip_src, ip_dst, port_src, port_dst):  # noqa: E501\n    \"\"\"\"\n    Copy data from one socket to another and retrieve TLS information\n    Inspired by https://stackoverflow.com/a/46422554\n    \"\"\"\n\n    try:\n        while not reader.at_eof():\n            data = await reader.read(8192)\n            if not len(data):\n                continue\n\n            # Rebuild the IP packet\n            tls_record = IP(dst=ip_dst, src=ip_src)\n            tls_record /= TCP(dport=port_dst, sport=port_src)\n            tls_record /= TLS(data)  # noqa: F821\n            peetch.globals.PACKETS_CAPTURED += [tls_record]\n\n            # Display a short summary\n            sprintf_fmt = \"%IP.src%:%TCP.sport% > %IP.dst%:%TCP.dport% %IP.proto%\"  # noqa: E501\n            summary = tls_record.sprintf(sprintf_fmt)\n            print(f\"    {direction} {summary}\")\n\n            # Copy data to the other socket\n            writer.write(data)\n\n            # Get and store TLS information\n            tls_version, ciphersuite, client_random, master_secret = retrieve_tls_information(peetch.globals.BPF_TLS_HANDLER, pid)  # noqa: E501\n            if ciphersuite:\n                if tls_version < 3:\n                    client_random_bytes = binascii.unhexlify(client_random)\n                    master_secret_bytes = binascii.unhexlify(master_secret)\n                    conf.tls_nss_keys = {\"CLIENT_RANDOM\": {client_random_bytes: master_secret_bytes}}  # noqa: E501\n                    peetch.globals.TLS_INFORMATION = {\"version\": tls_version,\n                                                      \"ciphersuite\": ciphersuite}  # noqa: E501\n    finally:\n        writer.close()\n\n\nasync def tcp_proxy():\n    \"\"\"\n    async TCP proxy\n    \"\"\"\n    server = await asyncio.start_server(handle_client, \"127.0.0.1\", 2807)\n    await server.serve_forever()\n\n\nasync def all_tasks(debug):\n    \"\"\"\n    all proxy tasks\n    \"\"\"\n    tasks = [tcp_proxy()]\n    if debug:\n        tasks += [dots()]\n    await asyncio.gather(*tasks)\n"
  },
  {
    "path": "peetch/utils.py",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nimport ctypes\nimport os\nimport os.path\nimport sys\n\n# Identify the library path\ndirname = os.path.dirname(__file__)\nUTILS_LIB_PATH = None\nfor root, dirs, files in os.walk(dirname):\n    for file in files:\n        if file.startswith(\"utils_lib\") and file.endswith(\".so\"):\n            UTILS_LIB_PATH = os.path.join(root, file)\n            break\n\n\nclass LIBSSLOffsets(ctypes.Structure):\n    _fields_ = [(\"ssl_session\", ctypes.c_uint64),\n                (\"ssl_cipher\", ctypes.c_uint64),\n                (\"master_secret\", ctypes.c_uint64),\n                (\"client_hello\", ctypes.c_uint64),\n                (\"client_random\", ctypes.c_uint64)]\n\n\nif UTILS_LIB_PATH:\n    libssl_offset = ctypes.CDLL(UTILS_LIB_PATH)\n    libssl_offset.libssl_offsets.argstypes = [ctypes.c_char_p, ctypes.c_uint16]\n    libssl_offset.libssl_offsets.restype = LIBSSLOffsets\n\n    def get_offsets(address_ipv4=b\"1.1.1.1\", port=443):\n        # Retrieve offsets inside SSL structures\n        raw_offsets = libssl_offset.libssl_offsets(address_ipv4, port)\n        return (raw_offsets.ssl_session,\n                raw_offsets.ssl_cipher,\n                raw_offsets.master_secret,\n                raw_offsets.client_hello,\n                raw_offsets.client_random)\nelse:\n    print(\"ERROR: cannot find the utils_lib dynamic library!\", file=sys.stderr)\n    sys.exit(1)\n\nif __name__ == \"__main__\":\n    print([\"0x%x\" % offset for offset in get_offsets()])\n"
  },
  {
    "path": "requirements.txt",
    "content": "scapy @ git+https://github.com/secdev/scapy@master\ncryptography\npyroute2\n"
  },
  {
    "path": "setup.py",
    "content": "# SPDX-License-Identifier: GPL-2.0+\n# Guillaume Valadon <gvaladon@quarkslab.com>\n\nfrom distutils.core import setup, Extension\n\nsetup(name=\"peetch\",\n      description=\"An eBPF playground\",\n      author=\"Guillaume Valadon\",\n      author_email=\"gvaladon@quarkslab.com\",\n      version=\"0.2.0\",\n      packages=[\"peetch\"],\n      package_data={\"peetch\": [\"ebpf_programs/peetch_*.c\"]},\n      entry_points={\"console_scripts\": [\"peetch=peetch:main\"]},\n      ext_modules=[Extension(\"peetch.utils_lib\", sources=[\"peetch/c_utils/libssl.c\"], libraries=[\"ssl\"])],\n      )\n"
  }
]